【问题标题】:How should I input search variables from React Client Side to Express Server Side API Call?我应该如何将搜索变量从 React 客户端输入到 Express 服务器端 API 调用?
【发布时间】:2020-03-15 14:04:58
【问题描述】:

我正在制作一个应用程序,用户可以在其中根据来自 Yelp Fusion API 的数据搜索要去的地方。不幸的是,由于可怕的 CORS 错误,我不得不将我的 API 调用转移到 Express 服务器。这是我希望应用程序现在如何工作的模型。

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

【问题讨论】:

    标签: javascript reactjs api express fetch


    【解决方案1】:

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

    关于来自客户端的 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.
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-18
      • 1970-01-01
      • 2012-01-12
      • 2011-10-12
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      相关资源
      最近更新 更多