【问题标题】:HTTP GET inside a api method called by the client客户端调用的 api 方法中的 HTTP GET
【发布时间】:2013-08-25 20:16:26
【问题描述】:

您好,我在 Nodejs 中设置了一个 REST API,并且 ajax 调用运行良好,直到我尝试从该方法中调用外部 REST 服务。

谁能帮我弄清楚为什么这不起作用?我正在使用在端口 3000 上运行 Express 的 Nodejs,基本上是 localhost。波纹管我正在进行的工作,但它已经改变了很多。我使用的是请求模块,但现在又回到了 http。

app.get('/api/exchange', function (req, res){
    var text = '';
    var options = {
        host : 'rate-exchange.appspot.com',
        port : 3000,
        path : '/currency?from=GBP&to=USD',
        method : 'GET'
    };

    var call = http.request(options, function(res) {
        console.log("statusCode: ", res.statusCode);
        text = "made it in";

        res.on('data', function(d) {
            text = "here";
        });
    });

    call.end();
    call.on('error', function(e) {
        text = "error";
    });

    res.json({ msg: text });
});

对不起我的classic javascript debuging technique,我基本上只是使用text 来看看它的去向。

当我运行它时,我会得到以下结果。

{
    "msg": ""
}

附言任何人都知道任何好的节点调试工具,我会很高兴的。

【问题讨论】:

  • 您的应用可能在 3000 上侦听,但在服务器上。 HTTP 流量可以通过 iptables、路由器或负载平衡器重定向。

标签: javascript node.js http rest express


【解决方案1】:

我猜port:3000 是错误的。你应该得到来自http.request回调函数的响应。

app.get('/', function (req, res){
    var text = '';
    var options = {
        host : 'rate-exchange.appspot.com',
        //port : 3000,
        path : '/currency?from=GBP&to=USD',
        method : 'GET'
    };

    var call = http.request(options, function(resp) {
        console.log("statusCode: ", res.statusCode);
        text = "made it in";

        resp.on('data', function(d) {
            text = "here";
            console.log("response data: "+d);
        });
    });

    call.end();
    call.on('error', function(e) {
        text = "error";
    });

    //res.json({ msg: text });
});

【讨论】:

  • 谢谢 :) 所以基本上发生的事情是我在得到结果之前就返回了,因为调用是异步的?
  • 是的。那,还有端口号。
猜你喜欢
  • 1970-01-01
  • 2014-01-11
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-20
相关资源
最近更新 更多