gpt4 book ai didi

node.js - 使用 Node JS 的调度程序

转载 作者:搜寻专家 更新时间:2023-10-31 23:18:32 26 4
gpt4 key购买 nike

我正在尝试做一个简单的服务器来响应 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: Cannot read property 'get' of 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 是否存在(就像您已经做的那样),并像您已经做的那样访问函数。

关于node.js - 使用 Node JS 的调度程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17296858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com