我在本地主机中有2个发布端点,我希望第一个端点通过发布请求获取参数,并将其传递给后者,然后后者将响应发送回第一个端点:
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”,错误号:“ ECONNREFUSED”,系统调用:“连接”,
地址:“ 127.0.0.1”,端口:80,配置:{适配器:[功能: httpAdapter], transformRequest:{'0':[Function:transformRequest]}, transformResponse:{'0':[功能:transformResponse]}, 超时:0, xsrfCookieName:'XSRF-TOKEN', xsrfHeaderName:'X-XSRF-TOKEN', maxContentLength:-1, validateStatus:[功能:validateStatus], 标头: {接受:“ application / json,text / plain, / ”, 'Content-Type':'application / json; charset = utf-8', '用户代理':'axios / 0.18.0', 'Content-Length':9}, 方法:“发布”, 网址:“ / b”, 数据:'{“ b”:“ c”}'} ....
答案 0 :(得分:1)
它引发异常的原因是axios请求的端口与服务器正在侦听的端口不同。您正在侦听端口3000(app.listen(3000)
),而axios发出请求的默认端口是端口80。因此,错误是Error: connect ECONNREFUSED 127.0.0.1:80
您需要做的是确保服务器正在侦听的端口与axios请求的端口相同。例如,将发布请求的代码行更改为
const text = await axios.post('http://localhost:3000/b', req.body);