设置一个基本的node.js服务器

时间:2012-04-02 16:26:16

标签: javascript node.js

我正在尝试设置一个基本的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次,对它正在做的事情充满信心,所以希望我能错过一些小事。谢谢!

1 个答案:

答案 0 :(得分:7)

我认为你不小心忘记了动词(要求)。

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