2015-12-23 50 views
0

我已經當我轉到http://localhost:1337/index.html這是正確顯示了服務器的NodeJS下面簡單的代碼....httpdispatcher不會回來,或空白resposne

var http = require('http'); 
var port = 1337; 
var dispatcher = require('httpdispatcher'); 

dispatcher.setStaticDirname(__dirname); 
dispatcher.setStatic(''); 

dispatcher.onGet("/page1", function (req, res) { 
    res.writeHead(200, { 'Content-Type': 'text/plain' }); 
    res.end('Page One'); 
}); 

var server = http.createServer().listen(port); 


server.on('request', function (req, res) { 
    console.log('GOT'); 
    dispatcher.dispatch(req, res); 
}); 
console.log('Listening on port %s', port); 

起來,但是當我做http://localhost:1337/page1什麼也沒有發生......如何我可以讓它正常工作...

回答

0

您需要在設置靜態調度程序之前定義您的自定義調度程序事件,在本例中爲「/ page1」。否則,靜態剩餘每一個可能的路徑來檢查文件系統。

dispatcher.onGet("/page1", function (req, res) { 
    res.writeHead(200, { 'Content-Type': 'text/plain' }); 
    res.end('Page One'); 
}); 

dispatcher.setStaticDirname(__dirname); 
dispatcher.setStatic(''); 

你修改後的代碼看起來就像這樣:

var http = require('http'); 
var port = 1337; 
var dispatcher = require('httpdispatcher'); 


dispatcher.onGet("/page1", function (req, res) { 
    res.writeHead(200, { 'Content-Type': 'text/plain' }); 
    res.end('Page One'); 
}); 

dispatcher.setStaticDirname(__dirname); 
dispatcher.setStatic(''); 

var server = http.createServer().listen(port); 

server.on('request', function (req, res) { 
    console.log('GOT'); 
    dispatcher.dispatch(req, res); 
}); 
console.log('Listening on port %s', port); 

測試和工程