標籤: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