我只是关注 http://www.nodebeginner.org/ 上的Node 初学者书籍 while I encound a TypeError。我已经搜索过,但没有人能解决这个错误。错误显示如下
D:\delbert\nodejs\proj\requestHandlers.js:7
response.writeHead(200, {"Content-Type":"text/plain"});
^
TypeError: Cannot call method 'writeHead' of undefined
at D:\delbert\nodejs\proj\requestHandlers.js:7:14
at ChildProcess.exithandler (child_process.js:635:7)
at ChildProcess.EventEmitter.emit (events.js:98:17)
at maybeClose (child_process.js:743:16)
at Socket.<anonymous> (child_process.js:956:11)
at Socket.EventEmitter.emit (events.js:95:17)
at Pipe.close (net.js:465:12)
和源代码:
//------------//
//服务器.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, request, response);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
//--------//
//索引.js//
//--------//
var server = require("./server");
var router = require("./route");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.start();
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);
//--------//
//路由.js//
//--------//
function route(handle, pathname, response) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response);
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;
//--------------------//
//requestHandlers.js//
//--------------------//
var exec = require("child_process").exec;
function start(response) {
console.log("Request handler 'start' was called.");
exec("ls -lah", function (error, stdout, stderr) {
response.writeHead(200, {"Content-Type":"text/plain"});
response.write(stdout);
response.end();
});
}
function upload(response) {
console.log("Request handler 'upload' was called.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello Upload");
response.end();
}
exports.start = start;
exports.upload = upload;
不知道错误是怎么来的。即使我粘贴书中的代码,它也卡在那里。
我试过了 TypeError: Cannot call method 'writeHead' of undefined和 http://cnodejs.org/topic/4fbca9123a7ec1d151038ac1但它们没有用。
你能帮帮我吗?
最佳答案
看来这本书确实有些错误。
以下是我立即发现的几个错误:
server.start()
像这样调用route()
:route(handle, pathname, request, response);
, 但route()
实际上是这样定义的:function route(handle, pathname, response)
(很可能是您特定错误的来源)
index.js
有handle["/"] = requestHandlers.start();
而不是handle["/"] = requestHandlers.start;
关于node.js - Node入门书TypeError : Cannot call method 'writeHead' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23061090/