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

时间:2013-06-22 13:07:19

标签: web-services node.js

我是node.js的新手。我的项目中有server.js,router.js,index.js和requestHandler.js文件。 我通过开始或上传网址如下

http://localhost:8888/start

我从url获取pathName并将其传递给服务器中的router.js,如下所示:

server.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;

router.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("./requestHandler");

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

server.start(router.route,handle);

requestHandler.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.

有什么问题?任何想法?

2 个答案:

答案 0 :(得分:1)

我在我的机器上尝试了你的代码(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

为什么遇到这个错误很棘手。你能检查一下节点版本吗?

根据您的日志数据,问题出在router.js中定义的函数route(handle,pathname)中。路径名的值从"/start"变为undefined。也许您需要调试此函数以找出原因。

答案 1 :(得分:0)

我也遇到了这个问题。好像我上次编辑后没有保存server.js。