Node.js http parse error

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   ar   問題   div   

 今天碰到一個奇怪的錯誤.

events.js:72        throw er; // Unhandled ‘error‘ event              ^Error: Parse Error    at Socket.socketOnData (http.js:1583:20)    at TCP.onread (net.js:527:27)

 

代碼如下: 

一個簡單的http伺服器

var http = require(‘http‘);var server = http.createServer();server.listen(3000);server.on(‘request‘, function(req, res){    res.writeHead(‘Content-Type‘, ‘text/html‘);    res.end(‘hello world‘);});

 

一段請求伺服器的代碼

var http = require(‘http‘);var req = http.request(‘http://localhost:3000‘);req.on(‘response‘, function(res){    res.setEncoding(‘utf8‘)    res.on(‘data‘, function(data){        console.log(data);    })})req.end();

 

問題出在這一行代碼

res.writeHead(‘Content-Type‘, ‘text/html‘);

 

正確的寫法是

res.writeHead(200, {‘Content-Type‘: ‘text/html‘});

 

如果伺服器端寫入了錯誤的header, 用戶端就不能正確解析, 報的錯誤就是"Parse Error".

 

Node.js文檔是這麼解釋req對象的error事件的

If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an ‘error‘ event is emitted on the returned request object.

 

如果Node.js的http module不能解析HTTP response, 一個error事件會被觸發, 這就是為什麼錯誤資訊中有"Unhandled ‘error‘ event".

 

在查這個bug過程中, 一個困惑我的地方是, 我寫的http請求代碼會出錯, 但是用瀏覽器開啟http://localhost:3000卻沒問題. 當你寫錯了代碼, 程式卻正常運行了, 這樣的bug最坑了.

Node.js http parse error

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.