客户端调用的api方法中的HTTP GET

时间:2013-08-25 20:16:26

标签: javascript node.js http rest express

您好我在Nodejs中设置了一个rest api,并且ajax调用工作正常,直到我尝试从该方法中调用外部REST服务。

任何人都可以帮我解决为什么这不起作用?我正在使用运行在端口3000上的Express的Nodejs,基本上是本地主机。贝娄我的工作正在进行中,但已经改变了很多。我正在使用请求模块,但现在又回到了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": ""
}

P.S。任何人都知道节点的任何好的debuging工具我会很高兴。

1 个答案:

答案 0 :(得分:2)

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