Reputation:
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
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.
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
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