我正在关注一本在线的 nodejs 书籍:http://nodebeginner.org/并停留在其中一个部分。在该部分 (http://nodebeginner.org/#head22),它要求我创建以下 4 个文件:
**index.js**:
var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {};
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);
**requestHandlers.js**:
function start(){
console.log("Request handler 'start' was called.");
return "Hello start";
}
function upload(){
console.log("Request handler 'upload' was called.");
return "Hello Upload";
}
exports.start = start;
exports.upload = upload;
**router.js**:
function route(handle, pathname){
console.log("About to route a request for " + pathname);
if(typeof handle[pathname] === 'function'){
handle[pathname]();
}else{
console.log("No request handler found for " + pathname);
return "404 Not found";
}
}
exports.route = route;
**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.");
response.writeHead(200, {"Content-Type":"text/plain"});
var content = route(handle, pathname);
response.write(content);
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
当我运行时,它会返回以下错误:
Server has started. Request for / received. About to route a request for / Request handler 'start' was called.
http2.js:598 throw new TypeError('first argument must be a string, Array, or Buffer'); ^ TypeError: first argument must be a string, Array, or Buffer at ServerResponse.write (http2.js:598:11) at Server.onRequest (/var/www/node/server.js:11:12) at Server.emit (events.js:70:17) at HTTPParser.onIncoming (http2.js:1451:12) at HTTPParser.onHeadersComplete (http2.js:108:31) at Socket.ondata (http2.js:1347:22) at TCP.onread (net_uv.js:309:27)
我可以将错误追溯到 server.js,当我注释掉这两行时,它起作用了:
var content = route(handle, pathname); response.write(content);
我哪里做错了?
最佳答案
你忘记在 router.js 的第 4 行返回值
handle[pathname]();
如果您将其更改为:它将正常工作:
return handle[pathname]();
关于node.js - Node.js 抛出 TypeError ('first argument must be a string, Array, or Buffer');,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7563982/