0

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"}' } ....

Harel.Lebel
  • 279
  • 6
  • 17

1 Answers1

2

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

Tianjiao Huang
  • 144
  • 3
  • 14
  • 1
    Thanks but I'm not able to send the response back from 'b' back to 'a' – Harel.Lebel Sep 03 '18 at 07:39
  • 2
    @Harel.Lebel This seems to be another problem in your code. You might want to change `res.send(text);` to `res.send(text.body);` in function `app.post('/a', ...){}`. https://stackoverflow.com/a/45341079/6438359 – Tianjiao Huang Sep 04 '18 at 05:42