简体   繁体   English

试图从后端到前端获取API数据

[英]Trying to get API data from backend to frontend

I've created an input form from my React front end and I've been able to send this data to my server using fetch. 我已经从我的React前端创建了一个输入表单,我已经能够使用fetch将这些数据发送到我的服务器。 From here I'm able to access it within my app.get() and pass the form data into my API function and ultimately when I console log the result I get the results that I want. 从这里我可以在我的app.get()中访问它并将表单数据传递给我的API函数,最终当我控制日志结果时,我得到了我想要的结果。 My problem now is I'm struggling to find a way to make this data accessible from my front end. 我现在的问题是我正在努力寻找一种方法来从我的前端访问这些数据。

I'm fairly stuck regarding what to do at this point, I thought that if I did something like response.send() within the api function that might work but it hasn't. 关于在这一点上做什么我很困惑,我想如果我在api函数中做了类似response.send()的东西,它可能有用,但它没有。 To my knowledge when you get the data you can send it to a particular endpoint with a POST request and then do a get request to that particular endpoint to get it back, but it doesn't seem that I'm able to do this in this case. 据我所知,当您获得数据时,您可以使用POST请求将其发送到特定端点,然后对该特定端点执行get请求以将其恢复,但似乎我无法在这个案例。

//From my front end react page, the front end data is a form:
handleSubmit(event: any){
 event.preventDefault();
 let location: string = this.state.location
 fetch('/', {
   method: 'POST',
   headers: {
     'Content-type': 'application/x-www-form-urlencoded'
   },
   body: location
 })
}


//From my server file:
app.use('/', express.static(path.resolve('client', 'dist')));
app.get('/', (req: any, response:any) => {
let city = Object.keys(req.body)[0]
 if (city.match(/[a-zA-z]/g)){ 
 console.log('string')
  api.locationToCoords(city, (result:Object) => {
   console.log(result)
   //response.send()
  })
 } else {
 //Geolocation
 let x = city.split(',')
 api.retrieveData(x[0], x[1], ((results:any) => {
   console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~')
   console.log('results: ',results)
 }))
}});

Simple fetch is like this, you can use this to get data on front-end 简单的fetch就是这样,你可以用它来获取前端的数据

fetch('your URL to fetch data', {
   method: 'POST',
   headers: {
        'Content-Type': 'application/json',
        // 'Content-Type': 'application/x-www-form-urlencoded',
   },
   body: formData //if any
})
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
  });

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

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