【问题标题】:pass body to internal http post request将正文传递给内部 http post 请求
【发布时间】:2018-09-02 20:32:22
【问题描述】:

我的本​​地主机中有 2 个 post 端点,我希望第一个通过 post 请求获取参数并将它们传递给后者,而后者会将响应发送回第一个:

    const axios = require('axios');
const express = require('express')
const app = express()
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({
    extended: false
}));

app.use(bodyParser.json());

app.post('/b', async (req, res, next) => {
    try {
        res.send(req.body);
    } catch (error) {
        console.log(error)
    }
})

app.post('/a', async (req, res, next) => {
    try {
        const text = await axios.post('/b', req.body);
        res.send(text);
    } catch (error) {
        console.log(error)
    }
})
app.listen(3000)

总是错误是:

{ Error: connect ECONNREFUSED 127.0.0.1:80
at Object.exports._errnoException (util.js:1033:11)
at exports._exceptionWithHostPort (util.js:1056:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1099:14)

代码:'ECONNREFUSED',errno:'ECONNREFUSED',系统调用:'connect',
地址:'127.0.0.1',端口:80,配置:{适配器:[功能: http适配器], 转换请求:{'0':[功能:转换请求]}, 转换响应:{'0':[功能:转换响应]}, 超时:0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', 最大内容长度:-1, 验证状态:[功能:验证状态], 标题: { Accept: 'application/json, text/plain, /', '内容类型': 'application/json;charset=utf-8', '用户代理':'axios/0.18.0', '内容长度': 9 }, 方法:'发布', 网址:'/b', 数据:'{"b":"c"}' } ....

【问题讨论】:

    标签: node.js http routing


    【解决方案1】:

    它抛出异常的原因是axios请求的端口与服务器正在监听的端口不同。您正在端口 3000 (app.listen(3000)) 上侦听,而 axios 向其发出请求的默认端口是端口 80。这就是为什么错误是 Error: connect ECONNREFUSED 127.0.0.1:80

    您需要做的是确保服务器正在侦听的端口与 axios 请求的端口相同。例如,将发出 post 请求的代码行更改为

    const text = await axios.post('http://localhost:3000/b', req.body);

    【讨论】:

    • 谢谢,但我无法将回复从“b”发送回“a”
    • @Harel.Lebel 这似乎是您代码中的另一个问题。您可能想在函数app.post('/a', ...){} 中将res.send(text); 更改为res.send(text.body);。 stackoverflow.com/a/45341079/6438359
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 2020-01-24
    • 2020-06-16
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多