How do I use axios within ExpressJS? How do I use axios within ExpressJS? express express

How do I use axios within ExpressJS?


Axios returns you the whole response, so if you try to send this you get a circular dependecy error.So on .then(data => res.json(data)), data is actually the response.

Try .then(response => res.json(response.data))


  1. You don't have to enclose your axios call in a try...catch as axios already has a catch block.

  2. Your express handler has to send a response back when axios gets a response from the API call or axios catches an error during the API call.

Your code should look something like this

router.get("/test", (req, res, next) => {  console.log("'/test' call");  axios.get("https://api.neoscan.io/api/main_net/v1/get_all_nodes")    .then(data => res.json(data))    .catch(err => next(err));})

If you fancy async...await, you can write your code like this

router.get("/test", async (req, res, next) => {  console.log("'/test' call");  try {    const res = await axios.get("https://api.neoscan.io/api/main_net/v1/get_all_nodes");    res.json(data);  }  catch (err) {    next(err)  }})


You forgot to respond to the client:

 try{    axios.get("https://api.neoscan.io/api/main_net/v1/get_all_nodes")           .then(data => res.status(200).send(data))           .catch(err => res.send(err)); } catch(err){    console.error("GG", err); }