Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send response from server side axios request to React/Redux app

I'm a little new to creating a backend in Node/Express, but I am trying use axios to make HTTP requests. I've set up express routes that will make the necessary request and I know from using Postman that GET request I'm testing does return a response. Where I'm stuck is how to return that data and send it to my React/Redux app to use.

-Server Side-

//Express Route
app.get('/api/recipes', recipeController.getRecipes)

//Controller Function that makes axios request
const axios = require('axios')
const Promise = require('bluebird')

module.exports = {
  getRecipes(req, res) {
      const url = "https://gw.hellofresh.com/api/recipes/search?country=us&limit=9"
      const token = "IUzI1NiIsInR5c"

      axios
      .get(url, {
        "headers": {"Authorization": "Bearer " + token}
      })
      .then((response) => {
        console.log(response)
      })
      .catch((err) => {
        console.log(err)
      })

  }
}

-Client Side-

I dispatch the following action and make a call using the endpoint I created. However, at this point, I'd get an error status even though on the server side I was able to get a response. I tried playing around using Promises as I read that axios GET requests returns promises, but couldn't wrap my head around on how to implement it.

export const getRecipes = () => {
  return (dispatch) => {
    axios
    .get('/api/recipes')
    .then((resp) => {
      console.log(resp)
    })
    .catch((err) => {
      console.log(err)
    })
  }
}
like image 811
jamesvphan Avatar asked Sep 29 '17 20:09

jamesvphan


People also ask

Can I use Axios on server-side?

One of the important capabilities of Axios is its isomorphic nature which means it can run in the browser as well as in server-side Node. js applications with the same codebase.


1 Answers

You need to call res.send in the route, to send the data to the client:

module.exports = {
  getRecipes(req, res) {
      const url = "https://gw.hellofresh.com/api/recipes/search?country=us&limit=9"
      const token = "IUzI1NiIsInR5c"

      axios
      .get(url, {
        "headers": {"Authorization": "Bearer " + token}
      })
      .then(response => {
        console.log(response)
        res.send(response) // <= send data to the client
      })
      .catch(err => {
        console.log(err)
        res.send({ err }) // <= send error
      })
  }
}
like image 142
alexmac Avatar answered Sep 27 '22 23:09

alexmac