node.js學習筆記(3)_極客學院_服務器入門

一.使用Http模塊創建Web服務器

1.Node.js的Web服務器的特點:

    不依賴其他特定的Web服務器軟件
    Node.js代碼處理請求的邏輯
    Node.js代碼負責Web服務器的各種'配置'
    var http = require('http'); // 引入http模塊

    var requestHandler = function (req ,res ) { //請求處理方法
        console.log('hahahaha');
        res.end('hello');
    };

    var  web = http.createServer(requestHandler);//創建一個服務器
    web.listen(3000);//設置監聽
    console.log("success: localhost:30000")

二.使用Express創建Web服務器

1.簡單的Express服務器:

var http = require('express'); // 引入express模塊

var app = express();

app.use(express.static('./public'));//靜態文件的處理,localhost:3000/test.txt


// 三種不同的路由配置
//--------------------------------Path
app.get('/',function (req,res) {
    res.end('Hello');
});
//--------------------------------多個子路由
var Router = express.Router();
// http://exaample.com/post/add
// http://exaample.com/post/list

Router.get('/add',function (req,res) {
    res.end('Router /add \n');
});
Router.get('/list',function (req,res) {
    res.end('Router /list \n');
});
app.use('/post',Router);
//--------------------------------//RESTful接口
app.route('/article')
    .get(function (req,res) {
        res.end('Router /article get\n');
    })
    .post(function (req,res) {
        res.end('Router /article post\n');
    })
//--------------------------------// 另一種風格的路徑處理
//e.g:http://example.com/news/123
app.param('newsId',function (req,res,next,newsId) {
    req.newsId = newsId; //直接將newsId加入到參數列表
    next();
});
app.get('/news/:newsId',function(req,res){
    res.end('newsId"' + newsId);
})
//--------------------------------


app.listen(3000,function afterListen() {
    console.log('express running on localhost:3000');
});

三.使用Net模塊創建Tcp服務器

    var net = require('net'); // 引入http模塊

    const PORT = '18000';
    const HOST = '127.0.0.1';

    var clientHandler = function (socket) {
        console.log('someone connected');

        socket.on('data',function dataHandler(data) {
            console.log(socket._remoteAddress,socket.remotePort,'send',data.toString()) ;
            socket.write('server received!'); //發送消息到客戶端
        })
        socket.on('close',function dataHandler() {
            console.log(socket._remoteAddress,socket.remotePort,'close') ;
        })
    };

    var app = net.createServer(clientHandler);

    app.listen(PORT,HOST);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章