【问题标题】:send request to other server from express node.js从 express node.js 向其他服务器发送请求
【发布时间】:2015-08-31 22:15:41
【问题描述】:

所以我试图从 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)? 但同样的错误信息被抛出。有谁知道这里可能出了什么问题?

【问题讨论】:

    标签: javascript node.js express routes request


    【解决方案1】:

    对于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();
        });
    });
    

    【讨论】:

    • 我在代码中犯了一个愚蠢的错误,并在应该是 end 的地方留下了 error。可能不会解决它,考虑到最后一个......但我想我至少会在这里做正确的事情,并摆脱我在这里倾倒的草率的东西。
    • 是的,还是同样的错误。我想知道是否可以从客户端获取请求中发出这种获取请求?
    • 另外,如果我删除 .on('end', fun...) 并放置类似 res.send('test') 或 res.render('test') 这样的东西,但是 res.send(response) 会引发相同的错误。相当混乱
    猜你喜欢
    • 2022-09-26
    • 2018-01-31
    • 2021-02-09
    • 2019-03-16
    • 2014-03-17
    • 1970-01-01
    • 2019-03-26
    • 2017-08-15
    • 1970-01-01
    相关资源
    最近更新 更多