我在尝试开始使用 Node.js 时正在查看这篇文章,我开始使用本指南来学习基础知识。
我的服务器的代码是:
var http = require('http');
http.createServer(function (request, response) {
request.on('end', function() {
response.writeHead(200, {
'Content-Type' : 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
当我转到localhost:8080(根据指南)时,我收到"未收到数据"错误。我看到一些页面说 https://是必需的,但返回"SSL 连接错误"。我不知道我错过了什么。
代码中的问题是永远不会触发"end"事件,因为您正在使用 Stream2 request
流,就好像它是 Stream1 一样。阅读迁移教程 - http://blog.nodejs.org/2012/12/20/streams2/
要将其转换为"旧模式流行为",您可以添加"data"事件处理程序或".resume()"调用:
var http = require('http');
http.createServer(function (request, response) {
request.resume();
request.on('end', function() {
response.writeHead(200, {
'Content-Type' : 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
如果你的例子是http GET处理程序,你已经有了所有的头,不需要等待body:
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {
'Content-Type' : 'text/plain'
});
response.end('Hello HTTP!');
}).listen(8080);
不要等待请求结束事件。直接来自 http://nodejs.org/略有修改:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Worldn');
}).listen(8080);