user12933680
user12933680

Reputation:

How to use router.get and https.get together? (Node.js)

I want to get information from the http request and send it to the frontend via the path '/ get'. I combined these 2 functions and it works but I don't think it is correct:

const router = express.Router();
const https = require('https');

router.get('/get', (req, res) => {
  https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
    let data = '';
    resp.on('data', (chunk) => {
      data += chunk;
    });
    resp.on('end', () => {
      res.json(JSON.parse(data).explanation)
    });
  }).on("error", (err) => {
    console.log("Error: " + err.message);
  });
});

Is there a better way to do this?

Upvotes: 0

Views: 340

Answers (2)

Sanket Vyawahare
Sanket Vyawahare

Reputation: 130

The better way would be to use Axios to make all your http requests to external apis which you want from nodejs application. It is a promise based request making library which you can use in browser as well as on backend server.

  1. Install axios using npm install axios
  2. axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY').then(response => res.send(response.data)).catch(error => console.log(error));

Upvotes: 0

Jonty Tejani
Jonty Tejani

Reputation: 1

No, it works fine.

But if you want another way, then use axios

you need to require axios and then add your request in the router.

const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

you get more information from here

Upvotes: 0

Related Questions