node.js - 如何使用 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);
});
尝试仅将硬编码值分配给端口。仍然没有运气
解决方案
您的代码中有很多错误。您已经部署了您的应用程序,但您的 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 上公开。随时从中获得帮助。存储库链接
推荐阅读
- c# - 如何使用 ASP.NET Core 3.1 实现自定义登录?
- python - 将 Python 浮点数转换为 C# 十进制数
- asp.net-core - 如何将下拉项发送到控制器而不是使用 ajax 填充的值
- reactjs - 使用 renderHooks 测试窗口
- python - 无法解决此错误:KeyError: NOUN
- python - 我永无止境的“while”循环正在运行,但在“重要”迭代时被追溯终止。Opensea 销售抓取机器人
- node.js - Mongoose - 通过特定字段查找文档的子数组
- javascript - Eclipse 2021/03 JavaScript 不支持
- powershell - Powershell Tile Horizontally 仅某些特定窗口
- flutter - 将 json 字符串转换为 json 对象时出错