Node.js服务器只是保持加载没有结果。

时间:2014-02-16 00:01:52

标签: javascript node.js postdata

我一直试图让我的服务器工作但是当我发送帖子数据时它只是继续加载而没有给出结果。这是我的noen.js文件。

var http = require('http');
var url = require('url');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  var queryData = url.parse(request.url, true).query;
  response.writeHead(200, {"Content-Type": "text/plain"});

  if (queryData.name) {
    // user told us their name in the GET request, ex: http://host:8000/?name=Tom
    var exec = require('child_process').exec;
    function puts(error, stdout, stderr) {sys.puts(stdout)}
    exec ("casperjs test.js " + queryData.name + '\n');

  } else {
response.end("Contact Admin - Not Working\n");
  }
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(1213);

任何人都可以帮我解决这个问题吗?当我去

127.0.0.1:8000/?name=tom 

我没有得到回应,页面只是进入一个长加载循环

2 个答案:

答案 0 :(得分:2)

没有响应。如果是真的话,那么响应“永不”结束。 写在if

的底部
response.end("something");

你会收到回应;

用于获取流程输出到响应:

https://stackoverflow.com/a/3944751/3018595

var http = require('http');
var url = require('url');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  var queryData = url.parse(request.url, true).query;
  response.writeHead(200, {"Content-Type": "text/plain"});

  if (queryData.name) {
    // user told us their name in the GET request, ex: http://host:8000/?name=Tom
    var exec = require('child_process').exec;

    exec ("casperjs test.js " + queryData.name + '\n',function(err, stdout, stderr) {

        response.end(stdout);

    });

  } else {
    response.end("Contact Admin - Not Working\n");
  }
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(1213);

答案 1 :(得分:0)

您的浏览器一直等待的原因是因为您没有结束您的回复。你必须调用response.end让你的服务器完成响应,否则它会一直认为响应还没有完成。我在你的if语句中添加了一行并测试了你的代码,它运行得非常好。

添加了行** response.end(“请求处理成功... \ n”); **,假设您需要显示不同的消息以防“else”语句。 我测试了网址http://:1213 /?name = tom

var http = require('http');
var url = require('url');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
var queryData = url.parse(request.url, true).query;
response.writeHead(200, {"Content-Type": "text/plain"});

if (queryData.name) {
// user told us their name in the GET request, ex: http://host:8000/?name=Tom
var exec = require('child_process').exec;
function puts(error, stdout, stderr) {sys.puts(stdout)}
exec ("casperjs test.js " + queryData.name + '\n');
response.end("Request processed successfully...\n");   


} else {
response.end("Contact Admin - Not Working\n");
}
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(1213);