deBhailis
deBhailis

Reputation: 75

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

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

Upvotes: 1

Views: 9376

Answers (1)

ravibagul91
ravibagul91

Reputation: 20755

Simple fetch is like this, you can use this to get data on front-end

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

Upvotes: 1

Related Questions