DEV Community

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

Posted on

1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay