繁体   English   中英

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

[英]Node.js tutorial web server not responding

我在尝试启动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 Connection Error'。 我无法弄清楚我错过了什么。

您的代码中的问题是“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处理程序,则您已经拥有所有标头,并且不需要等待正文:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM