【问题标题】:Nodejs http request not workingNodejs http请求不起作用
【发布时间】:2013-12-09 19:41:02
【问题描述】:

我有一段代码应该执行 http 获取请求。程序成功退出,没有错误,但我没有看到任何响应,甚至没有进入回调函数!一开始我以为是因为http是异步的,最后放了一个大循环,但这也没有用。有谁知道这个问题?只有第一个控制台日志 sendHttpRequest 和 444 被打印出来。我也尝试了 http.get 但它也不起作用。

function sendHttpRequest (url, callBack) {
    console.log("sendHttpRequest");
    //constrct options
    var options = {
        host: 'www.google.com',
        path: '/index.html',
        method: 'GET',
        headers: {
           'Content-Type': 'application/x-www-form-urlencoded'
        }
    };

    http.get("http://www.google.com/index.html", function(res) {
        console.log("Got response: " + res.statusCode);
    });

    var req = http.request(options, function(res) {
        console.log("333");
        var output = '';
        console.log(options.host + ':' + res.statusCode);
        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            console.log("DATATATAT!")
            output += chunk;
        });

        res.on('end', function () {
            console.log('222');
            var obj = JSON.parse(output);
            callBack(res.statusCode, obj);
        });
    });

    req.on('error', function (err) {
        console.log('error: ' + err.message);
    });

    req.end();
    console.log("444");
    }
}

【问题讨论】:

  • 有人说google没有“/index.html”,我把它删了还是不行。它甚至没有进入回调内部。没有回应。
  • 你怎么称呼这个?这有一些问题,但除此之外,我会看到所有console.log,并且还会调用回调函数。您还返回了 HTML,JSON.parse 将永远无法工作。
  • @making3 嗨,我把它包装成一个模块并从一个 grunt 任务中调用它,但不知何故,我只看到第一个控制台日志和最后一个,即 444。我必须打电话grunt 或此模块中的异步等待响应?谢谢!对于 json 部分,本来我是要解析一个 json 的,这样就不会有问题了。
  • @making3 感谢 r3mus,我找到了问题所在。这是因为 grunt 任务在我得到 http 请求的响应之前就终止了。现在我添加了异步和回调来解决这个问题!也非常感谢您的帮助! :)

标签: node.js http get


【解决方案1】:

更新

grunt 任务在 OP 收到响应之前终止;添加async 和一个回调到任务修复它。


如果我将您的代码放在函数之外并添加 var http = require('http');,我会在 222 之前收到响应,此时它会以 SyntaxError: Unexpected token < 终止。这实际上正在死去,因为您试图将 HTML 响应解析为 JSON。

如果您将整个脚本粘贴到下面并端到端运行,控制台将终止:

undefined:1
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
^
SyntaxError: Unexpected token <
    at Object.parse (native)
    at IncomingMessage.<anonymous> (/Users/you/nodetest/tmp/test.js:31:28)
    at IncomingMessage.EventEmitter.emit (events.js:120:20)
    at _stream_readable.js:896:16
    at process._tickCallback (node.js:599:11)

脚本:

var http = require('http');

console.log("sendHttpRequest");
//constrct options
var options = {
    host: 'www.google.com',
    path: '/index.html',
    method: 'GET',
    headers: {
       'Content-Type': 'application/x-www-form-urlencoded'
    }
};

http.get("http://www.google.com/index.html", function(res) {
    console.log("Got response: " + res.statusCode);
});

var req = http.request(options, function(res) {
    console.log("333");
    var output = '';
    console.log(options.host + ':' + res.statusCode);
    res.setEncoding('utf8');

    res.on('data', function (chunk) {
        console.log("DATATATAT!")
        output += chunk;
    });

    res.on('end', function () {
        console.log('222');
        // it's failing on the next line, because the output 
        // it's receiving from Google is HTML, not JSON. 
        // If you comment out this line and simply 
        // "console.log(output)" you'll see the HTML response.
        var obj = JSON.parse(output);
        callBack(res.statusCode, obj);
    });
});

req.on('error', function (err) {
    console.log('error: ' + err.message);
});

req.end();
console.log("444");

【讨论】:

  • 嗨,我把它包装成一个模块并从一个 grunt 任务中调用它,但不知何故我只看到第一个控制台日志和最后一个,即 444。我必须调用 async in咕噜声或此模块等待响应?谢谢!对于 json 部分,本来我是要解析一个 json 的,这样就不会有问题了。
  • 您将需要在您的问题中提供包装器,以便我实际确定 - 开箱即用,您可以看到这是有效的,但如果您的 grunt 任务在此之前终止完成(并且这是异步运行),这是一个不错的选择,grunt 不会等待它完成。
  • 事实证明你是对的!在我得到响应之前,grunt 任务终止了!我向它添加了异步和回调并且它起作用了。非常感谢!! :)
  • 好东西!很高兴听到它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-23
  • 2018-04-24
  • 2016-09-21
  • 1970-01-01
相关资源
最近更新 更多