2013-08-05 169 views
1

我試圖在節點中發送一個http響應以在瀏覽器中打印結果。簡化的源代碼如下。基本上,所有的變量都是在程序的某個地方定義的,所以這不應該成爲問題。當我嘗試運行該腳本,我不斷收到錯誤:在node.js中發送HTTP響應

http.js:783 
     throw new TypeError('first argument must be a string or Buffer'); 

    TypeError: first argument must be a string or Buffer 

所以有人可以熟悉的node.js或JavaScript語法讓我知道是什麼問題?

upload = function(req, res) { 
     var fileInfos = [obj, obj]; //defined as an array of objects 
     var counter = 0;   
     counter -= 1; 
     if (!counter) {     
      res.end({files: fileInfos}); //files is defined. 
     } 
     }; 

    async.forEach(urls, downloadFile, function (err) { //all params defined. 
     if(err){ 
      console.error("err"); 
      throw err; 
     } 
     else{ 
      http.createServer(function(req, res){ 
      upload(req1, res);      //req1 defined as an array of objects. 
     }).listen(3000, "127.0.0.1"); 
     console.log('Server running at http://127.0.0.1:3000/'); 
    } 
    }); 

回答

1

這個錯誤通常是由試圖調用response.write了錯誤類型的參數引起的。看着它表明的文檔:

response.end([data], [encoding])#

This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.

If data is specified, it is equivalent to calling response.write(data, encoding) followed by response.end().

現在response.write(chunk, encoding)預計該塊作爲一個字符串,所以看起來可能是當你調用res.end({files: fileInfos})它無法寫入該對象的內容作爲一個字符串。

+0

好點!非常感謝答案! – jensiepoo

1

在將JavaScript對象發送給客戶端之前,可以使用JSON.stringify()將JavaScript對象轉換爲字符串。

res.end(JSON.stringify({files: fileInfos})); 
相關問題