HTTP GET位于客户端调用的api方法内部

HTTP GET inside a api method called by the client

本文关键字:api 方法 内部 调用 客户端 GET HTTP      更新时间:2023-09-26

嗨,我在Nodejs中设置了一个rest api,ajax调用运行良好,直到我尝试从该方法中调用外部rest服务。

有人能帮我弄清楚为什么这不起作用吗?我使用Nodejs,Express运行在端口3000上,目前基本上是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": ""
}

附言:如果有人知道node的任何好的调试工具,我会非常棒。

我猜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 });
});