簡體   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