DEV Community

ಮಿಥುನ್
ಮಿಥುನ್

Posted on

using axios in nodejs

axios is Promise based Http Client for the browser and node.js

install axios into your nodejs project using below command.


    npm install axios

Enter fullscreen mode Exit fullscreen mode

import axios using below statement.


     const axios = require('axios');

Enter fullscreen mode Exit fullscreen mode

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
  })
})

Enter fullscreen mode Exit fullscreen mode

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");
    })

Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)