2011-09-27 35 views
4

我正在关注一个nodejs在线书:http://nodebeginner.org/,并且卡在其中一个部分。在该节(http://nodebeginner.org/#head22),它要求我创建以下4个文件:Nodejs引发TypeError('第一个参数必须是字符串,数组或缓冲区');

**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); 

我在哪里做错了?

+0

http://stackoverflow.com /问题/ 14835582 /的NodeJS先参数-必须待一个串 - 或缓冲 - 时 - 使用 - 响应 - 写入瓦特 –

回答

11

你忘了对router.js

handle[pathname](); 

,如果你将其更改为它将正常工作的4号线返回值:

return handle[pathname](); 
相关问题