2012-04-02 77 views
0

我想設置一個基本的node.js服務器,並得到一個錯誤,我無法弄清楚。我有4個文件:index.js,server.js,router.js,requestHandlers.js設置一個基本的node.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 // code never never got here

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次,對它正在做的事情感到非常自信,所以希望只有一些我想念的小事情。謝謝!

+0

如何分享錯誤? – Hubro 2012-04-02 16:32:40

+0

我在錯誤代碼的地方發表了評論。我的對象屬性回來了,因爲undefined – 2012-04-02 16:36:37

回答

7

我想你不小心忘記了動詞(要求)。

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

我新的它是一個小東西。謝謝 – 2012-04-02 16:38:01

+1

@ nic-meiring如果這個答案解決了你的問題,請把它標記爲正確答案 – Hubro 2012-04-02 16:44:43

+0

哎對不起。當它最初得到回答時,標記爲正確爲時尚早。現在標記了 – 2012-04-02 20:51:35