上一節咱們構建了一個基礎的 http 服務器,咱們能夠接收 http 請求,可是咱們得作點什麼吧 – 不一樣的 http 請求,服務器應該有不一樣的響應。node
處理不一樣的 http 請求在咱們的代碼中是一個不一樣的部分,叫作路由選擇。瀏覽器
咱們要爲路由提供請求的 url 和其餘須要的 get 及 post 參數,隨後路由根據這些數據來執行相應的代碼,所以,咱們須要查看 http 請求,從中提取出請求的 url 以及 get/post 參數。服務器
咱們須要的全部數據都會包含在 request 對象中,該對象做爲回調函數(onRequest)的第一個參數傳遞。想要解析 request 對象中的數據就須要調用 url 模塊或者 querystring 模塊,該兩個模塊都是 nodejs 的內置模塊。函數
var http = require('http'); var url = require('url'); function start() { function onRequest(request, response) { console.log(url.parse(request.url).pathname); response.writeHead({ 'Content-type': 'text/plain' }); response.write('Hello node.js'); response.end(); } http.createServer(onRequest).listen(8888); console.log('server start...'); } exports.start = start;
在瀏覽器中輸入 http://localhost:8888/start 經過終端咱們能夠看到請求的 url 路徑,經過 url 路徑爲基準映射到不一樣的處理程序上。如今咱們能夠來寫路由模塊(route.js)了。post
function route(pathname) { console.log('route: ' + pathname); } exports.route = route;
有了路由模塊,那麼咱們把路由和服務器整合起來,首先擴展 server.js:ui
var http = require('http'); var url = require('url'); function start(route) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; route(pathname); response.writeHead({ 'Content-type': 'text/plain' }); response.write('Hello node.js'); response.end(); } http.createServer(onRequest).listen(8888); console.log('server start...'); } exports.start = start;
擴展 index.jsurl
var server = require('./server'); var route = require('./route'); server.start(route.route);
在終端開啓服務器 node index
,能夠看到終端輸出的內容正是路由模塊裏面的內容,說明咱們的 http 服務器已經在使用路由模塊了,並會將請求的路徑傳遞給路由:spa
node index server start... route: /start route: /favicon.ico