2016-07-07 33 views
0

我創建了以下服務器的NodeJS:添加新的路徑,服務器的NodeJS

var http = require('http'); 

var serverFunction = function(req, res) { 
    if (req.url === '/') { 
     //does something 
    } 
} 

http.createServer(serverFunction).listen(3000); 

現在我想添加另一條路徑(例如:/你好),但我不希望改變serverFunction。

我該怎麼做?

回答

2

創建多個獨立請求處理程序的更高級別的方法是使用a simple framework like Express。雖然在技術上不需要做你想問的問題,但Express可以讓這樣的任務變得簡單。

多路由執行一個簡單的Express服務器應該是這樣的:

var express = require('express'); 
var app = express(); 

app.get('/', function(req, res) { 
    // handle the/route here 
}); 

app.get('/hello', function(req, res) { 
    // handle the /hello route here 
}); 

app.listen(3000); 

捷運框架是建立在允許你添加路由一樣簡單,如上圖所示。它還包含了許多,有更多的功能,如中間件處理,並獲得大量的預建的中間件模塊,如cookie處理,會話處理,後處理等...


嚴格回答您的原問題(儘管我不認爲這是添加更多路由處理程序的最簡單方法),但如果您想使用普通http模塊,而不是將第二條路線添加到現有的偵聽器,則可以在服務器上偵聽request event

var http = require('http'); 

var serverFunction = function(req, res) { 
    if (req.url === '/') { 
     //does something 
    } 
} 

var server = http.createServer(serverFunction).listen(3000); 

server.on('request', function(req, res) { 
    // see all incoming requests here 
    if (req.url === '/hello') { 
     // process /hello route here 
    } 
}); 

事實上,如果你看過http server doc carefully,你會看到你的serverFunction只不過是一個自動註冊監聽器多爲request事件和與事件式的接口,你可以創建更多的聽衆事件,如果你選擇。

+0

您的解決方案非常完美!謝謝! – leonero

0

假設您要使用低級別的NodeJS HTTP API。您可以使用函數組合將多個處理程序組合到一個處理程序中。如果req.url不匹配,則每個處理程序應該將執行結果傳遞給下一個處理程序。

var http = require('http'); 

var handler1 = function(req, res) { 
    res.writeHead(200, { 'Content-Type': 'text/html' }); 
    res.write('/'); 
    res.end(); 
} 

var handler2 = function(req, res) { 
    res.writeHead(200, { 'Content-Type': 'text/html' }); 
    res.write('/Hello'); 
    res.end(); 
} 

var middleware = compose([wrapHandler('/', handler1), 
         wrapHandler('/hello', handler2)]); 

http.createServer(middleware).listen(3000); 

function wrapHandler(path, cb) { 
    return function (req, res, next) { 
     if (req.url === path) { 
      cb(req, res); 
     } else { 
      next(); 
     } 
    }; 
} 

function notFoundHandler(req, res) { 
    res.writeHead(404, { 'Content-Type': 'text/html' }); 
    res.write('No Path found'); 
    res.end();  
}; 

// adapted from koa-compose 
function compose(middleware) { 
    return function (req, res){ 
     let next = function() { 
      notFoundHandler.call(this, req, res); 
     }; 

     let i = middleware.length; 
     while (i--) { 
      let thisMiddleware = middleware[i]; 
      let nextMiddleware = next; 
      next = function() { 
       thisMiddleware.call(this, req, res, nextMiddleware); 
      } 
     } 
     return next(); 
    } 
}