gpt4 book ai didi

web-services - Node.js 参数未正确传递给路由器

转载 作者:搜寻专家 更新时间:2023-11-01 00:02:43 25 4
gpt4 key购买 nike

我是 node.js 的新手。我的项目中有 server.js 、 router.js 、 index.js 和 requestHandler.js 文件。我像下面这样在 url 中传递开始或上传

http://localhost:8888/start

我从 url 获取 pathName 并将其传递给服务器中的 router.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;

路由器.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 ;

索引.js:

var server = require("./Server");
var router = require("./router");
var requestHandlers = require("./requestHandler");

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

server.start(router.route,handle);

请求处理程序.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;

我得到错误的结果:

PS C:\Program Files\nodejs> node ..\..\Users\private\Desktop\hello\index.js
Server has started.
Request for /start received.
About to route a request for /start
No request handler found for undefined
Request for /favicon.ico received.
About to route a request for /favicon.ico
No request handler found for undefined
Request for /favicon.ico received.
About to route a request for /favicon.ico
No request handler found for undefined

而不是这个:

Server has started.
Request for /start received.
About to route a request for /start
Request handler 'start' was called.

问题是什么?有什么想法吗?

最佳答案

我在我的机器上试过你的代码 (Mac OS X + v0.8.9)。它运作良好。控制台输出为:

Server has started.
Request for /start received.
About to route a request for /start
Request handler 'start' was called.
Request for /favicon.ico received.
About to route a request for /favicon.ico
No request handler found for /favicon.ico

遇到错误的原因很棘手。你能检查你的 Node 版本吗?

根据您的日志数据,问题出在 router.js 中定义的函数 route(handle,pathname) 中。 pathname 的值从 "/start" 更改为 undefined。也许你需要调试这个函数来找出原因。

关于web-services - Node.js 参数未正确传递给路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17251084/

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