How to interact with another API running on a different port with Node?

0

Good afternoon guys,

I'm having to create 3 micro services on nodejs, but I still have not been able to interact with them. Ex: I have 3 APIs that two are clients of the first one, I want to know how I make interaction between them being that the 3 run on different ports.

    
asked by anonymous 14.01.2018 / 15:36

1 answer

0

You will have to do HTTP request like any other. Ex.:

const http = require('axios')
const appsConfig = require('./microServicesConfig')
const xxxURI = 'http://localhost' + appsConfig.xxx.port
const yyyURI = 'http://localhost' + appsConfig.yyy.port

http.get(xxxURI + '/metodo-endpoint')
  .then(response => ({
    attr: response.data.attr,
    attr2: response.data.attr2
  }))

http.get(yyyURI + '/metodo-endpoint')
  .then(response => ({
    attr: response.data.attr,
    attr2: response.data.attr2
  }))

You can also use a local server with proxy-reverse, eliminating the need to specify the port: Example with nginx:

server {
    listen       80;
    server_name  localhost;    
    location /xxx {
        proxy_pass http://127.0.0.1:5000;
    }
    location /yyy {
        proxy_pass http://127.0.0.1:3000;
    }
}

then:

const http = require('axios')

http.get('/xxx/metodo-endpoint')...
http.get('/yyy/metodo-endpoint')...
    
17.01.2018 / 18:58