Nodejs抛出TypeError('第一个参数必须是字符串,数组或缓冲区');

时间:2011-09-27 03:43:41

标签: node.js

我正在关注一个在线的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;

当我跑步时,它会返回以下错误:

  

服务器已启动。请求/收到。即将发送请求   for / Request处理程序'start'被调用。

     

http2.js:598       抛出新的TypeError('第一个参数必须是字符串,数组或   缓冲');             ^ TypeError:第一个参数必须是字符串,数组或   缓冲       在ServerResponse.write(http2.js:598:11)       在Server.onRequest(/var/www/node/server.js:11:12)       在Server.emit(events.js:70:17)       在HTTPParser.onIncoming(http2.js:1451:12)       在HTTPParser.onHeadersComplete(http2.js:108:31)       在Socket.ondata(http2.js:1347:22)       在TCP.onread(net_uv.js:309:27)

我可以将错误跟踪到server.js,当我注释掉这两行时,它可以工作:

    var content = route(handle, pathname);
    response.write(content);

我在哪里做错了?

1 个答案:

答案 0 :(得分:11)

您忘记返回router.js第4行的值

    handle[pathname]();

如果将其更改为:

,它将正常工作
    return handle[pathname]();