我想設置一個基本的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次,對它正在做的事情感到非常自信,所以希望只有一些我想念的小事情。謝謝!
如何分享錯誤? – Hubro 2012-04-02 16:32:40
我在錯誤代碼的地方發表了評論。我的對象屬性回來了,因爲undefined – 2012-04-02 16:36:37