httpdispatcher返回no或空白响应

时间:2015-12-23 07:43:34

标签: node.js

我有一个nodejs服务器的简单代码....

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/index.html时它正确显示但是当我http://localhost:1337/page1没有任何反应时......我怎样才能让它正常运行......

1 个答案:

答案 0 :(得分: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);

经过测试和工作