6

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)
    })
  }
}
jamesvphan
  • 195
  • 1
  • 4
  • 14

1 Answers1

8

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
      })
  }
}
alexmac
  • 19,087
  • 7
  • 58
  • 69