简体   繁体   English

React 将数据从前端传递到后端节点

[英]React pass data from front-end to back-end node

I'm trying to learn a little bit more of REACT and APIs.我正在尝试更多地学习 REACT 和 API。 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.我使用的是 NASA API,到目前为止,我可以拨打电话返回当天的 NASA 图片以及随机日期的图像。 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但我不太确定如何将该日期从输入传递到请求 API 调用的后端

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这是 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 nasa-api 获取

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)

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.你应该再有一个 axios 从 React 调用到你的 NodeJS,因为 React(front-end) 和 NodeJS(back-end) 将是两个不同的东西。

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. 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.

You want to take the date state from your client and send it to your API endpoint through a POST request.您想从客户端获取日期 state 并通过 POST 请求将其发送到您的 API 端点。 Your API endpoint will then take the date from the req.body and insert that into it's own request to the NASA API.然后,您的 API 端点将从 req.body 获取日期并将其插入到它自己对 NASA API 的请求中。 Your API will await the NASA API's response and send that back to the client once it is received.您的 API 将等待 NASA API 的响应,并在收到响应后将其发送回客户端。

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)
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM