简体   繁体   中英

How should I input search variables from React Client Side to Express Server Side API Call?

I'm making an app where user can search for places to go to based off of data from the Yelp Fusion API. Unfortunately I had to move my API call to an Express server because of the dreaded CORS error. Here's a model of how I want the app to work now.

  1. Client Side: user inputs search term and location
  2. Search term and location are sent to Server Side.
  3. Server Side: Makes API call using information and sends data back to Client Side.
  4. Client Side: displays results.

I've been stuck for a few days on how to implement this and it's proving extremely difficult to find information or examples on someone doing the same thing. When I try to make a push request from the Client Side to the local host address where the Express Server is I keep receiving a 404 Error and "Not Found" text, but the GET request works perfectly fine, however I still can't input any new search queries to get new data. The Yelp API takes in two parameters which you always have to use called "term" and "location". These are the parameters I'm trying to pass from the client side to the serverside to make the call. I'm really just looking for answers on ways I could implement this. Thanks!

// My Client side call in React passing in parameters.

    makeCall = (term, location) => {
const yelppost = new URL("http://localhost:5000/"),
  params = { term: term, location: location };

Object.keys(params).forEach(key =>
  yelppost.searchParams.append(key, params[key])
);
const response = fetch(yelppost, {
  method: "POST"
});
response
  .then(resp => console.log(resp))
  // .then(data => console.log(data[0]))
  // .then(data => console.log(data))
  .catch(error => console.log(error.message));};

//Server Side call in Express

    const express = require("express");
    const cors = require("cors");
    require("dotenv").config();
    const json = require("body-parser").json;
    const urlEncoded = require("body-parser").urlencoded;
    const fetch = require("node-fetch");
     const app = express();

     app.use(json());
     app.use(urlEncoded({ extended: true }));
     app.use(cors());

     app.get("/", (req, res) => {
     const yelp = new URL("https://api.yelp.com/v3/businesses/search"),
     params = { term: "", location: "" };

     Object.keys(params).forEach(key =>
      .searchParams.append(key, params[key])
       );

      const response = fetch(yelp, {
      headers: {
           Authorization: `Bearer ${process.env.REACT_APP_YELP_API_KEY}`
         }
         });

     response
       .then(resp => resp.json())
       .then(data => res.send(data.businesses))
       .catch(error => console.log(error.message));
      });

    app.listen(5000, () => {
     console.log("Server running on 5000");
     });

It is because it cannot find an endpoint with a post request. You have specified an app.get in your express app. It should be app.post instead. It is the reason why your get request works.

With regards to the api call from the client side you can still hit your express endpoint with a GET request instead of POST. You client side request will be:

fetch(`http://localhost:5000?term=${term}&location=${location}`)
      .then(res => res.json())
      .then(
        (result) => {
          //do stuff with the result
        },
        (error) => {
          //do stuff when error
        }
      )

In the above request for the url you can use string literals instead which can incorporate dynamic values in a string as we did for location and term.

Then your express endpoint for yelp will be as follows:

   app.get("/", (req, res) => {
       // destructure the request to get query which contains your term and location.
       const {query} = req; 

       // get term and location from the query that we added in the url from the client request and use it in your yelp endpoint.
       const yelpUrl = `https://api.yelp.com/v3/businesses/searchterm=${query.term}&location=${query.location}`;
   //Make the request from here to yelp and you should be good to go.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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