6

我在尝试开始 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 连接错误”。我无法弄清楚我错过了什么。

4

2 回答 2

11

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

要将其转换为“旧模式流行为”,您可以添加“数据”事件处理程序或“.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 处理程序,则您已经拥有所有标头并且不需要等待正文:

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {
    'Content-Type' : 'text/plain'
  });
  response.end('Hello HTTP!');
}).listen(8080);
于 2013-11-13T01:37:44.537 回答
1

不要等待请求结束事件。直接来自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);
于 2013-11-13T01:36:52.867 回答