2011-09-27 2 views
4

온라인 상태 인 nodejs 책 다음에 : http://nodebeginner.org/과 섹션 중 하나에 붙어 있습니다.Nodejs가 TypeError를 throw합니다 ('첫 번째 인수는 문자열, 배열 또는 버퍼 여야 함).

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)

:

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

내가 실행, 그것은 나에게 다음과 같은 오류를 반환 : 해당 섹션 (http://nodebeginner.org/#head22)에서는 다음의 4 개 가지 파일을 만들 나를 필요

나는 server.js하는 오류를 추적 할 수 있고, 나는이 2 개 라인을 주석 처리 할 때, 그것은 작동 : 어디에서 잘못하고있는 중이 야

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

?

+0

http://stackoverflow.com/questions/14835582/nodejs-first-argument-a-string-or-buffer-using-response-write-w –

답변

11

당신은 router.js

handle[pathname](); 

당신이 그것을 변경하는 경우 제대로 작동의 4 번째 줄에 값을 반환 잊고있어 :

return handle[pathname](); 
관련 문제