Nithya Neela
Nithya Neela

Reputation: 75

How to read API from one node server to another Node server using http?

I have two node applications running on localhost:4000 and localhost:5001.

I would like to read Employee collection from localhost:4000 to localhost:5001.

How to achieve it?

I tried this, https://flaviocopes.com/node-make-http-requests/

But no success.

const https = require('https')
const options = {
hostname: 'localhost',
port: 4000,
path: '/employee',
method: 'GET'
}

const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)

res.on('data', (d) => {
 process.stdout.write(d)
})
})

req.on('error', (error) => {
console.error(error)
})

req.end()

I expect to read all employees from the Employees collection. but it shows the error as follows

Error: write EPROTO 9996:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:332:

at WriteWrap.afterWrite [as oncomplete] (net.js:788:14) errno: 'EPROTO', code: 'EPROTO', syscall: 'write' .

Do we have http to do this.

Upvotes: 0

Views: 827

Answers (1)

Vinil Prabhu
Vinil Prabhu

Reputation: 1289

Use axios, it can be used in client as well as server application.

const axios = require('axios');

callApi = (req, res) => {
    axios.get("http://localhost:5001",
              { headers: { key:value }, params: { key:value } }
    ).then((response) => {
        res.status(200).send(response.data);
    }).catch((error) => {
        console.log(error);
        res.status(400).send(error.message);
    });
};

you can also use post, just change axios.get to axios.post and add another body object after url

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  },
   { headers: { key:value }, params: { key:value } })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Upvotes: 1

Related Questions