从express node.js向其他服务器发送请求

时间:2015-08-31 22:15:41

标签: javascript node.js express routes request

所以我试图将来自express node.js的请求发送到另一个URI:

router.get('/', function (req, res, next) {
    http.get(URI, function(response) {
        console.log("Got response: " + response.statusCode);
        res.send(response);
    }).on('error', function(e) {
        console.log("Got error: " + e.message);
    });
});

这将发回一条错误消息,如下所示:

GET http://localhost:3000/login (anonymous function) @ 
loginButton.js:48getSync @ loginButton.js:34(anonymous function) @ 
loginButton.js:22
loginButton.js:25 DOMException: Failed to execute 'send' on 
'XMLHttpRequest': Failed to load 'http://localhost:3000/login'.
at Error (native)
at http://localhost:3000/javascripts/index/loginButton.js:48:13
at getSync 
(http://localhost:3000/javascripts/index/loginButton.js:34:12)
at HTMLButtonElement.<anonymous> 
(http://localhost:3000/javascripts/index/loginButton.js:22:13)

我已尝试将其更新为以下建议: how to send Post request from node.js to another server ( java)? 但是抛出了相同的错误消息。有谁知道这里可能出现什么问题?

1 个答案:

答案 0 :(得分:0)

使用http.getresponse是一个流。因此,您需要构建对象的整个主体(从流中连接块),或者您需要使用流式传输的方法。

在express中,res.send将发送数据并关闭连接。它假定您已发送了整个有效负载。

使用.send而不是使用.write,而是直接发送传入的块。

调整后的代码如下所示:

router.get('/', function (req, res, next) {
    http.get(URI, function(response) {
        res.write(response);
    }).on('end', function() {
        res.end();
    });
});
相关问题