axios is Promise based Http Client for the browser and node.js
install axios into your nodejs project using below command.
npm install axios
import axios using below statement.
const axios = require('axios');
Below sample code to shows how to use axios. since axios returns promise object handle success and error data with then() and catch() callback functions.
app.get("/yourapi", function(req, res, next) => {
axios.get("https://replace/your/url/here")
.then(function (response) {
// handle success
return res.send(response.data);
})
.catch(function (error) {
// handle error
console.log(error);
// return res.send(error["message"]); // send response or
next(error); // pass error to global error handler
})
})
global error handler example. make sure you use error handler middleware at the end of entry script file(index/server.js file).
app.use(function (err, req, res, next) {
res.status(500).send(err["message");
})
References
Top comments (0)