简体   繁体   English

我应该如何从 React 客户端输入搜索变量到 Express 服务器端 API 调用?

[英]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.我正在制作一个应用程序,用户可以根据来自 Yelp Fusion API 的数据搜索 go 的位置。 Unfortunately I had to move my API call to an Express server because of the dreaded CORS error.不幸的是,由于可怕的 CORS 错误,我不得不将我的 API 调用移动到 Express 服务器。 Here's a model of how I want the app to work now.这是我希望应用程序现在如何工作的 model。

  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.服务器端:使用信息调用 API 并将数据发送回客户端。
  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.当我尝试从客户端向 Express 服务器所在的本地主机地址发出推送请求时,我不断收到 404 错误和“未找到”文本,但 GET 请求工作得非常好,但我仍然无法输入任何新的搜索查询以获取新数据。 The Yelp API takes in two parameters which you always have to use called "term" and "location". Yelp API 接受两个参数,您总是必须使用它们,称为“术语”和“位置”。 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.你已经在你的 express 应用中指定了一个 app.get。 It should be app.post instead.它应该是 app.post 。 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.关于来自客户端的 api 调用,您仍然可以使用 GET 请求而不是 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.在上面对 url 的请求中,您可以使用字符串文字代替,它可以将动态值合并到字符串中,就像我们对位置和术语所做的那样。

Then your express endpoint for yelp will be as follows:然后,您的 yelp 快速端点将如下所示:

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

暂无
暂无

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

相关问题 搜索过滤器,我应该在客户端还是服务器端执行? - Search Filter, should I do it client side or server side? 应该在客户端使用 react 还是在服务器端使用 express 路由器来制作路由器? - Should one Make routers on client side using react or using express router on server side? 从客户端调用服务器端功能 - Call server side function from Client Side Express,如何将变量从路由传递到客户端的JS文件 - Express, how to pass variables from routes to JS file that is in the client side 如何在客户端Javascript中调用Node / Express API密钥(.env)? - How do I call a Node/Express API key (.env) in Client-side Javascript? 如何从客户端调用服务器端按钮单击功能? - How can i call a server side button click function from client side? 如何将数据从客户端表单输入传输到服务器端Nodejs脚本? - How do I transfer data from a client-side form input to a server-side Nodejs script? 如何在React-Express Node App中将对象从服务器发送到客户端组件 - How to send objects from server to client side components in react-express node app 身份验证,使用Express JS比较从客户端输入的数据与服务器端的mySql - Authentication, Compare data input from client side with mySql in server side using express JS 在 express js 中显示从服务器端到客户端的警报框,react js - showing an alert box from server side to client side in express js, react js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM