繁体   English   中英

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

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

我正在制作一个应用程序,用户可以根据来自 Yelp Fusion API 的数据搜索 go 的位置。 不幸的是,由于可怕的 CORS 错误,我不得不将我的 API 调用移动到 Express 服务器。 这是我希望应用程序现在如何工作的 model。

  1. 客户端:用户输入搜索词和位置
  2. 搜索词和位置被发送到服务器端。
  3. 服务器端:使用信息调用 API 并将数据发送回客户端。
  4. 客户端:显示结果。

我在如何实现这一点上被困了几天,事实证明很难找到有关某人做同样事情的信息或示例。 当我尝试从客户端向 Express 服务器所在的本地主机地址发出推送请求时,我不断收到 404 错误和“未找到”文本,但 GET 请求工作得非常好,但我仍然无法输入任何新的搜索查询以获取新数据。 Yelp API 接受两个参数,您总是必须使用它们,称为“术语”和“位置”。 这些是我试图从客户端传递到服务器端以进行调用的参数。 我真的只是在寻找有关如何实现这一点的答案。 谢谢!

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

这是因为它找不到带有发布请求的端点。 你已经在你的 express 应用中指定了一个 app.get。 它应该是 app.post 。 这就是您的获取请求有效的原因。

关于来自客户端的 api 调用,您仍然可以使用 GET 请求而不是 POST 来访问您的快速端点。 您的客户端请求将是:

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

在上面对 url 的请求中,您可以使用字符串文字代替,它可以将动态值合并到字符串中,就像我们对位置和术语所做的那样。

然后,您的 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.

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