我正在尝试设置基本的node.js服务器,但遇到了我无法弄清的错误。我有4个文件:index.js,server.js,router.js,requestHandlers.js

index.js

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

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

server.start(router.route, handle);


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"); // 2nd log-- works fine

    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."); //1st log -- works fine

};
exports.start = start;


router.js

function route(handle, pathname) {
    console.log("About to route a request for " + pathname); //3rd log -- works fine
    console.log(handle); // THIS IS THE PROBLEM returns ---> { '/': undefined, '/start': undefined, '/upload': undefined }
    console.log(pathname); //works fine -- returns "/"
    console.log(typeof handle[pathname]); //undefined
    if (typeof handle[pathname] === 'function') {
        handle[pathname](); //never called because above evaluates to undefined
    }
    else {
        console.log("No request handler found for " + pathname);
    }
}

exports.route = route;


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;


我走了100遍,对它所做的事情充满信心,因此希望我缺少一些小事情。谢谢!

最佳答案

我认为您不小心忘记了动词(require)。

var requestHandlers = require("./requestHandlers");

关于javascript - 设置基本的node.js服务器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9980087/

10-11 07:12