Localhost没有响应简单节点应用程序

时间:2014-06-10 20:41:53

标签: node.js localhost

我是使用node的新手,我正在尝试编写一个简单的应用程序(见下文),但是当我尝试在浏览器中访问它时,它只是永远加载而且什么都没发生。有谁知道如何解决这一问题?我查看了一些网站和其他教程,但到目前为止还没有任何工作。有人告诉我导航到这个链接:http://localhost:8080/?data=put_some_text_here

以下是代码:

    //include http module, add url module for parsing
    var http = require("http"),
        url = require("url");

    //create the server
    http.createServer(function(request, response) {
      //attach listener on end event
      request.on('end', function() {
        //parse the request for arguements and store them in _get variable
        //this function parses the url form request and returns obj representation
        var _get = url.parse(request.url, true).query;
        //write headers to the response
        response.writeHead(200, {
         'Content-Type': 'text/plain'
        });
        //send data and end response.
        response.end('Here is your data: ' + _get['data']);  
      });
    }).listen(8080);

2 个答案:

答案 0 :(得分:1)

您没有从请求中读取任何数据,因此永远不会调用您的end事件处理程序,这意味着您永远不会结束响应。如果您不关心请求数据,则可以在request.resume();之前完成request.on('end', ...);

答案 1 :(得分:0)

你在结束活动中附加监听器但不会触发此事件。

//include http module, add url module for parsing
var http = require("http"),
    url = require("url");

//create the server
http.createServer(function(request, response) {

    //parse the request for arguements and store them in _get variable
    //this function parses the url form request and returns obj representation
    var _get = url.parse(request.url, true).query;
    //write headers to the response
    response.writeHead(200, {
        'Content-Type': 'text/plain'
    });

    //send data and end response.
    response.end('Here is your data: ' + _get['data']);

    //attach listener on end event
    request.on('end', function() {
        //you can do something here
        console.log('Event: Request End', request.url);
    });

}).listen(8080);