首页 > 解决方案 > 如何使用 axios 在 react.js 端处理后端动态分配的端口?

问题描述

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

在控制台中获取http://localhost:5000/user/login/email/password net::ERR_CONNECTION_REFUSED。

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

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

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

标签: node.jsreactjsmern

解决方案


您的代码中有很多错误。您已经部署了您的应用程序,但您的 URL 仍然是 localhost,而不是 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;

我在 MERN 中创建了一个应用程序,并在 GitHub 上公开。随时从中获得帮助。存储库链接


推荐阅读