当前位置: 首页 > 知识库问答 >
问题:

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

澹台博文
2023-03-14
    null
// 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");
     });

共有1个答案

张嘉佑
2023-03-14

这是因为它找不到具有post请求的终结点。您已经在express应用程序中指定了app.get。应该改为app.post。它是get请求工作的原因。

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

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的请求中,您可以使用字符串文本来代替,它可以将动态值合并到字符串中,就像我们对位置和术语所做的那样。

   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.
}
 类似资料:
  • 我正在尝试使用ExpressJS和Coffeescript制作一个网络应用程序,它从亚马逊、LastFM和必应的网络应用程序接口中提取数据。 用户可以从特定乐队请求特定专辑的价格、即将到来的音乐会时间和乐队的位置等数据,等等...诸如此类的东西。 我的问题是:我应该使用和在客户端进行这些API调用,还是应该在服务器端进行?我已经完成了客户端请求;我如何从服务器端进行API调用 我只想知道最佳实践是

  • 尝试使用Express将参数从服务器端传递到Node.js中的客户端。 但到目前为止什么都没起作用。你们要怎么做?非常感谢你的帮助:)

  • 嘿,伙计们,我目前已经实现了一个路线,负责根据他的请求从我的服务器上检索信息,现在我有兴趣将我的对象转移到坐在我视图中的客户端脚本。我可以使用Res.Render传输对象吗?

  • 我想在一些计算机之间建立点对点连接,这样用户就可以在没有外部服务器的情况下聊天和交换文件。我最初的想法如下: 我在服务器上制作了一个中央服务器插座,所有应用程序都可以连接到该插座。此ServerSocket跟踪已连接的套接字(客户端),并将新连接的客户端的IP和端口提供给所有其他客户端。每个客户端都会创建一个新的ServerSocket,所有客户端都可以连接到它。 换句话说:每个客户端都有一个Se

  • 我正在创建我的产品,并与这个问题。有一天,我设置了Socket.io,一切都很好。第二天,我将服务器和客户端从http迁移到HTTPS。迁移后客户端和服务器端仍然连接,但不能从客户端发射到服务器,从服务器发射到客户端。 我的ssl证书位于和中,它们加载正确。运行在上的服务器 我的示例react组件。我的react应用程序运行在上。HTTPS连接良好,工作良好。 我该怎么办?也许我在中错误地使用了s