简体   繁体   中英

pass body to internal http post request

I have 2 post endpoints in my localhost and I want that the first will get parameters by a post request and will pass them to the latter, and the latter will send back the response to the first:

    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)

and always the error is :

{ 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)

code: 'ECONNREFUSED', errno: 'ECONNREFUSED', syscall: 'connect',
address: '127.0.0.1', port: 80, config: { adapter: [Function: httpAdapter], transformRequest: { '0': [Function: transformRequest] }, transformResponse: { '0': [Function: transformResponse] }, timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, validateStatus: [Function: validateStatus], headers: { Accept: 'application/json, text/plain, / ', 'Content-Type': 'application/json;charset=utf-8', 'User-Agent': 'axios/0.18.0', 'Content-Length': 9 }, method: 'post', url: '/b', data: '{"b":"c"}' } ....

The reason that it throws an exception is that the port axios requesting is not same as the port the server is listening. You are listening at port 3000 ( app.listen(3000) ) while the default port that axios makes requests to is port 80. So that's why the error is Error: connect ECONNREFUSED 127.0.0.1:80

What you need to do is to make sure that the port that the server is listening is same as the port that axios is requesting to. For example, change the line of the code that you make the post request to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM