调度程序与节点JS

我试图做一个简单的服务器应答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
if(this.listener [method] [parsedUrl.pathname])this.listener [method] [parsedUr ^ TypeError:无法读取属性'get'undefined

有人知道为什么

这可能是一个错字

 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是否存在(就像你已经做的那样),并像你已经做的那样访问函数。

好吧,你build议的方式工作; 我还有最后一个问题。 我已经添加了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”消息,但是在控制台中我得到:

[function]find未定义的错误收听器!

所以首先find侦听器,但是之后也被称为errorListener; 如果我点击重新加载页面,在控制台上,我只有两个行([function]和发现),没有更多的错误听众!…你知道为什么我第一次加载一个页面,即使我得到正确的导致浏览器,调度程序调用erroListener?