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

时间:2015-06-07 11:21:44

标签: javascript node.js

我在node.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;

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;

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('./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?

THX!

1 个答案:

答案 0 :(得分:1)

可能是因为您从不调用启动或上传功能。尝试在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;

希望这有帮助。