如何使用 axios 在 react.js 端处理后端动态分配的端口?

How to deal with backend dynamically allocated ports on react.js side using axios?

今天早上,我在 heroku 中成功部署了一个 MERN 堆栈登录应用程序。但是,当我尝试登录时

GET http://localhost:5000/user/login/email/password net::ERR_CONNECTION_REFUSED in the console.

我知道这个错误是因为我在 axios 中使用

发出 get 请求
    axios.get("http://localhost:5000/user/login/" + this.state.email + "/" + this.state.password).then((res) => {
                if (res.status === 200) {
                    this.setState({ status: res.status, name: res.data.name });
                    console.log(res.data);
                }
                else
                    throw new Error(res.status);
            }).catch((err) => {
                this.setState({ isInvalid: true });
            })

但是,端口是在服务器端动态分配的。

    const port = process.env.PORT||5000;

    app.listen(port, () => {
        console.log("Server started on port:" + port);
    });

尝试仅将硬编码值分配给端口。仍然没有运气

首先我建议你,登录时不要使用get请求方式。 其次,如果您已经部署了后端代码,那么使用 heroku 提供的动态 url 进行登录请求。 例如如果你的 url 是 xyz.heroku.com 那么 axios.get('xyz.heroku.com/user/login/'+email+'/'+password); 现在您不需要对端口进行硬编码或使用本地主机。

你的代码中有很多错误。您已经部署了您的应用程序,但您的 URL 仍然是本地主机,而不是 Heroku URL。首先,您需要像这样为您的应用程序设置 env 变量。

你可以把它放在你得到终点的某个常量文件中。不要直接在 ajax 调用中写入 END POINTS。使用常量并创建一个文件,用于执行应用程序的所有 ajax 调用。

您可以为前端和后端设置 env,这就是您的工作方式。开发环境应该与生产环境分开。

if (process.env.NODE_ENV === "development") {
  API = "http://localhost:8000";
} else if (process.env.NODE_ENV === "production") {
  API = "https://be-prepared-app-bk.herokuapp.com";
}

不要在参数中使用 GET 登录和发送电子邮件和密码。您应该使用 POST 并在正文中发送所有数据。

您的单个 ajax 文件应该如下所示:

import { API_HOST } from "./constants";
import * as auth from "../services/Session";

const GlobalAPISvc = (endPoint, method, data) => {
  const token = auth.getItem("token");
  const uuid = auth.getItem("uuid");
  return new Promise((resolve, reject) => {
    fetch(`${API_HOST}${endPoint}`, {
      method: method,
      body: JSON.stringify(data),
      headers: {
        "Content-Type": "application/json",
        "x-authentication": token,
        uuid: uuid
      }
    })
      .then(res => {
        return res.json();
      })
      .then(json => {
        resolve(json);
      })
      .catch(error => {
        reject(error);
      });
  }).catch(error => {
    return error;
  });
};

export default GlobalAPISvc;

我在 GitHub 上 public 在 MERN 中创建了一个应用程序。随时从中寻求帮助。 Repository Link