gpt4 book ai didi

javascript - node.js 请求处理程序不会调用函数

转载 作者:太空宇宙 更新时间:2023-11-04 00:54:19 25 4
gpt4 key购买 nike

我正在node.js中迈出第一步,并在尝试路由我的服务器收到的请求时遇到了问题。我的项目中有以下文件,全部位于同一层次结构级别:

服务器.js:

var http = require('http');
var url = require('url');

function start(route,handle){
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received");

route(handle,pathname);

response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.")
}

exports.start = start;

requestHandlers.js:

function start(){
console.log("Request handler 'start' was called");
}

function upload(){
console.log("Request handler 'upload' was called");
}

exports.start = start;
exports.upload = upload;

路由器.js:

function route(handle,pathname){
console.log("About to route a request for" + pathname );
if (typeof handle[pathname] === 'function'){
handle[pathname];
} else {
console.log('No request handler found for' + pathname);
}
}

exports.route = route;

最后一个是index.js:

var server = require('./server');
var router = require('./router');
var requestHandlers = require('./requestHandlers');


var handle = {};
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;


server.start(router.route,handle);

例如,当我在浏览器中输入 URL“localhot:8888/start”时,我会在控制台中看到以下内容:

Server has started.
Request for /upload received
About to route a request for/upload
Request for /favicon.ico received
About to route a request for/favicon.ico
No request handler found for/favicon.ico

但为什么我要看到我希望从 upload()start() 函数中看到的 console.log?

谢谢!

最佳答案

这可能是因为您从未调用启动或上传函数。尝试在 router.js 中的 handle[pathname] 之后添加一些括号,如下所示:

function route(handle,pathname){
console.log("About to route a request for" + pathname );
if (typeof handle[pathname] === 'function'){
handle[pathname]();
} else {
console.log('No request handler found for' + pathname);
}
}

exports.route = route;

希望这有帮助。

关于javascript - node.js 请求处理程序不会调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30692923/

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