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

时间:2021-04-30 00:27:19

标签: javascript node.js reactjs

我正在努力学习更多的 REACT 和 API。我正在使用 NASA API,到目前为止,我可以打电话返回当天的 NASA 照片以及随机日期的图像。 我现在想做的是让“用户”选择一个日期。但我不确定如何将该日期从输入传递到请求 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>

这是控制器

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 获取

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

路线

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

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

2 个答案:

答案 0 :(得分:1)

你应该再有一个从 React 到 NodeJS 的 axios 调用,因为 React(前端)和 NodeJS(后端)将是两种不同的东西。

要么你直接从 React 调用 NASA API(这将在前端公开你的 API Key),要么 React axios 调用你的 NodeJS,然后 NodeJS axios 调用(API Key)到 NASA API。

答案 1 :(得分:0)

您希望从客户端获取日期状态并通过 POST 请求将其发送到您的 API 端点。然后,您的 API 端点将从 req.body 中获取日期并将其插入到它自己对 NASA API 的请求中。您的 API 将等待 NASA API 的响应,并在收到响应后将其发送回客户端。

客户

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

服务器

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)
  })
})
相关问题