11

我是 nodeJS 的新手,并试图学习它。
我正在尝试从http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/执行 hello world 示例, 但我没有得到任何输出,并且我在 chrome 上收到 No data received 页面浏览器。
我已经在我的 PC 上安装了 apache(XAMPP),但它没有激活,而且当我尝试node http.js在终端中运行时,我没有得到任何输出。
我有另一个文件,hello.js,其中包含console.log('Hello World!'); 我运行时在终端中node hello.js获取输出。Hello World!http.js不工作。
http.js 代码:

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

2 回答 2

28

我想您使用节点 0.10.x 或更高版本?它在 api 上有一些变化stream,通常称为 Streams2。Streams2 中的一项新功能是在end您完全使用流(即使它是空的)之前永远不会触发事件。

如果您真的想发送end事件请求,您可以使用 Streams 2 API 使用流:

var http = require('http');

http.createServer(function (request, response) {

   request.on('readable', function () {
       request.read(); // throw away the data
   });

   request.on('end', function () {

      response.writeHead(200, {
         'Content-Type': 'text/plain'
      });

      response.end('Hello HTTP!');
   });

}).listen(8080);

或者您可以将流切换到旧(流动)模式:

var http = require('http');

http.createServer(function (request, response) {

   request.resume(); // or request.on('data', function () {});

   request.on('end', function () {

      response.writeHead(200, {
         'Content-Type': 'text/plain'
      });

      response.end('Hello HTTP!');
   });

}).listen(8080);

否则,您可以立即发送响应:

var http = require('http');

http.createServer(function (request, response) {

  response.writeHead(200, {
     'Content-Type': 'text/plain'
  });

  response.end('Hello HTTP!');
}).listen(8080);
于 2013-10-26T15:49:26.760 回答
5

尝试这个

//Lets require/import the HTTP module
var http = require('http');

//Lets define a port we want to listen to
const PORT=8080; 

//We need a function which handles requests and send response
function handleRequest(request, response){
    response.end('It Works!! Path Hit: ' + request.url);
}

//Create a server
var server = http.createServer(handleRequest);

//Lets start our server
server.listen(PORT, function(){
    //Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", PORT);
});
于 2016-09-24T18:34:48.277 回答