David Cibin
David Cibin

Reputation: 21

React pass data from front-end to back-end node

I'm trying to learn a little bit more of REACT and APIs. I'm using a NASA API and so far I'm able to make a call a return the NASA pic of the day as well an image from a random date. What I would like to do now is to have an option that let the "user" pick a date. But I'm not really sure how to pass that date from the input to the back-end where the API call are requested

class NasaDaily extends Component {
  state = {
    dailyPics: [],
    randomPic: [],
    date: ''
  }
  async componentDidMount() {
    const dailyPics = await getDailyPics();
    const randomPic = await getRandomPic();
    this.setState({ dailyPics })
    this.setState({ randomPic })
  }

  render() {

    return (
      <>

        <input
          name="date"
          id="date"
          min="1995-06-16"
          type="date"
          className="active"
          value={this.state.date}
          onChange={event => this.setState({ date: event.target.value })}
        >
        </input>

here's the controller

const start = new Date(1995, 6, 16)
const end = new Date()
function randomDate(start, end) {
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()))
}

async function nasaRandom(req, res) {
  const randDate = randomDate(start, end).toISOString().slice(0, 10)
  axios.get(`https://api.nasa.gov/planetary/apod?api_key=${process.env.REACT_APP_API_KEY_NASA}&date=${randDate}`)
    .then(response => res.json(response.data))
}

nasa-api fetch

export function getRandomPic() {
  return fetch('/api/')
    .then(res => res.json())
}

route

const router = require('express').Router();
const ctrl = require('../controllers/nasa')

router.get('/', ctrl.nasaRandom)

Upvotes: 0

Views: 1491

Answers (2)

UncleHooptie
UncleHooptie

Reputation: 31

You want to take the date state from your client and send it to your API endpoint through a POST request. Your API endpoint will then take the date from the req.body and insert that into it's own request to the NASA API. Your API will await the NASA API's response and send that back to the client once it is received.

Client

await axios({
  method: "POST",
  url: "yourAPI/customDate",
  data: {
    date: this.state.date 
  },
  withCredentials: false
}).then((response) => {
  //response from your API that includes the NASA API image
})

Server

router.post("/customDate", async (req, res) => {
  const customDate = req.body.date
  await axios({
    method: "GET",
    url: `https://api.nasa.gov/planetary/apod?api_key=${process.env.REACT_APP_API_KEY_NASA}&date=${customDate}`,
    withCredentials: false
  }).then((response) => {
    res.send(response.image)
  })
})

Upvotes: 1

GanHJ
GanHJ

Reputation: 330

You should have one more axios call from the React to your NodeJS as React(front-end) and NodeJS(back-end) will be two different things.

It is either you call directly from React to NASA API (which will exposed your API Key in the front-end) or React axios call to your NodeJS and then NodeJS axios call (API Key) to NASA API.

Upvotes: 1

Related Questions