簡體   English   中英

React API 在開發中調用工作並在生產構建中失敗

[英]React API calls work in development and fail in production build

我正在嘗試使用 Spring Boot/Hibernate Restful CRUD API 部署一個 React 項目。 我在本地運行 SQL 數據庫並在開發模式下運行我的 React 應用程序 (localhost:3000) 允許與我的 API 成功通信。

但是,當我構建我的生產應用程序 (localhost:5000) 時,API 不成功。 API 響應是錯誤代碼 304。我最好的猜測是端口的變化與某些東西混淆了? 它在端口:3000 上按預期工作,在端口:5000 上構建時失敗。

我以前從未部署過 React 應用程序,所以感謝您的幫助!


API 調用

   const apiCall = () => {
    fileService
      .getUsers()
      .then((response) => {
        setUsers(response.data); //Incorrectly returns a 304 error
      })
      .catch(function (error) {
        console.log(error);
      });
  };

獲取用戶()

    getUsers() {
        return service.getRestClient().get("/api/getAllUsers");
    }

獲取休息客戶端()

getRestClient() {
    if (!this.serviceInstance) {
      this.serviceInstance = axios.create({
        baseURL: "http://localhost:5000/",
        timeout: 10000,
        headers: {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE",
          "Access-Control-Allow-Headers": "Content-Type",
          "Access-Control-Allow-Credentials": true,
        },
      });
    }
    return this.serviceInstance;
  }

自發布以來,我了解到您不能在 React 的生產版本中使用代理。 package.json 中的"proxy:"僅在開發中有效 - 在生產中無效。 感謝大家的幫助。

來源: https://create-react-app.dev/docs/proxying-api-requests-in-development/

Ben,首先,我認為您需要確保您的后端確實在 5000 上運行,然后您需要使用 postman、高級 REST Z8A5DA52ED1264747D35AZ9E70C3A8A8 等工具嘗試一個簡單的請求。

也許,您需要釋放計算機(防火牆)上的 5000 端口。

其他想法是,您需要指定一些標志來使用其他請求 ip/端口,在我的情況下,我使用 angular 並且我需要一些標志:

ng serve --host 0.0.0.0 --disable-host-check

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM