我正在尝试一个简单的服务器回答url / page1和/ page2; 这是模块dispatcher.js:
var HttpDispatcher = function() {
this.listeners = { get: [ ], post: [ ] };
this.errorListener = function() { }
}
HttpDispatcher.prototype.on = function(method, url, cb) {
this.listeners[method].push({
cb: cb,
url: url
});
}
HttpDispatcher.prototype.onGet = function(url, cb) {
this.on('get', url, cb);
}
HttpDispatcher.prototype.onPost = function(url, cb) {
this.on('post', url, cb);
}
HttpDispatcher.prototype.onError = function(cb) {
this.errorListener = cb;
}
HttpDispatcher.prototype.dispatch = function(req, res) {
var parsedUrl = require('url').parse(req.url, true);
var method = req.method.toLowerCase();
if(this.listener[method][parsedUrl.pathname]) this.listener[method][parsedUrl.pathname](req, res)
else this.errorListener(req, res);
}
module.exports = new HttpDispatcher();
这是服务器:
var dispatcher = require('./node_modules/httpdispatcher');
var http = require('http');
dispatcher.onGet("/page1", function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Page One');
});
dispatcher.onPost("/page2", function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Page Two');
});
http.createServer(function (req, res) {
dispatcher.dispatch(req, res);
}).listen(80, '127.0.0.1');
但是当我尝试执行服务器时,我收到错误:
D:\ Works \ Web Resources \ NODE JS \ node_modules \ httpdispatcher.js:33
如果(this.listener [方法] [parsedUrl.pathname]) this.listener [方法] [parsedUr ^ TypeError:无法读取未定义的属性'get'
任何人都知道为什么?
答案 0 :(得分:3)
这可能是一个错字
if(this.listener[method][parsedUrl.pathname]) this.listener[method][parsedUrl.pathname](req, res)
我认为它是this.listeners
(带-s)
第二个问题(来自评论):
HttpDispatcher.prototype.on = function(method, url, cb) {
this.listeners[method][url] = cb;
}
这样,您可以检查URL是否存在(就像您已经做过的那样),并像您一样访问该功能。
答案 1 :(得分:0)
好的,你的建议方式; 我有最后一个问题;我已经添加了3个console.log:
HttpDispatcher.prototype.dispatch = function(req, res) {
var parsedUrl = require('url').parse(req.url, true);
var method = req.method.toLowerCase();
console.log(this.listeners[method][parsedUrl.pathname]);
if (this.listeners[method][parsedUrl.pathname])
{
this.listeners[method][parsedUrl.pathname](req, res);
console.log('Found');
}
else
{
this.errorListener(req, res);
console.log('ERROR LISTENER!');
}
}
现在,当我向URL 127.0.0.1/page1请求消息" Page One"浏览器正确显示,但在控制台中我得到:
[功能] 发现 未定义 ERROR LISTENER!
首先找到侦听器,但后来也称为errorListener;如果我点击重新加载页面,在控制台上我只得到两行([功能]和找到),没有更多错误的听众!...你知道为什么我第一次加载页面,即使我得到正确的结果在浏览器中,调度程序调用也是erroListener?