Node.js教程Web服务器没有响应

我正在查看这篇文章,试图开始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); 

当我去本地主机:8080(每个指南),我得到一个'没有数据收到'的错误。 我已经看到一些页面说https://是必需的,但是返回一个'SSL连接错误'。 我无法弄清楚我错过了什么。

代码中的问题是,“end”事件永远不会被触发,因为您正在使用Stream2 requeststream,就好像它是Stream1一样。 阅读迁移教程 – http://blog.nodejs.org/2012/12/20/streams2/

要将其转换为“旧模式stream行为”,您可以添加“数据”事件处理程序或“.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 World\n'); }).listen(8080);