2014-02-12 32 views
1

问题是关于Node.js的问题。我是新手,遵循教程,并且教程的第一个Node脚本在我的系统(Hello World)上成功运行。现在,我复制并粘贴了本教程第二部分的代码(创建一个http服务器),并试图通过端口8080连接到本地主机上,但我的浏览器(Chrome)返回了一个错误。Node.js初学者教程脚本 - 错误代码:ERR_EMPTY_RESPONSE

错误代码:ERR_EMPTY_RESPONSE

所以,我真的不知道什么是错在这里。我会假设我正确安装了Node,因为我的第一个脚本运行正常。也许这是一个简单的初学者错误,我错过了它。

下面是脚本:

// Include http module. 
var http = require("http"); 

// Create the server. Function passed as parameter is called on every request made. 
// request variable holds all request parameters 
// response variable allows you to do anything with response sent to the client. 
http.createServer(function (request, response) { 
    // Attach listener on end event. 
    // This event is called when client sent all data and is waiting for response. 
    request.on("end", function() { 
     // Write headers to the response. 
     // 200 is HTTP status code (this one means success) 
     // Second parameter holds header fields in object 
     // We are sending plain text, so Content-Type should be text/plain 
     response.writeHead(200, { 
      'Content-Type': 'text/plain' 
     }); 
     // Send data and end response. 
     response.end('Hello HTTP!'); 
    }); 
// Listen on the 8080 port. 
}).listen(8080); 

我保存这一个文件,server.js,导航到在命令提示符正确的目录,并没有任何错误执行节点server.js。

问题可能是什么?

+0

你以下什么教程? –

+0

http://code.tutsplus.com/tutorials/nodejs-for-beginners--net-26314 @HectorCorrea – CuriousWebDeveloper

回答

0

这应该让你开始:

var http = require("http"); 

http.createServer(function (request, response) { 

    console.log(request.url); 
    response.writeHead(200, { 
     'Content-Type': 'text/plain' 
    }); 
    response.end('Hello HTTP!'); 

}).listen(8080); 
+0

解决了它。谢谢,教程脚本有什么问题? – CuriousWebDeveloper

+0

我真的不明白为什么本教程中的代码不工作*除非*你为'request.on('data')'添加了一个处理程序,如其他教程所示:http://docs.nodejitsu .com/articles/HTTP/servers/how-to-read-POST-data –

+1

如果您查看教程链接的第一条评论,则会很好地解释问题。 – CuriousWebDeveloper