Ben*_*n L 3 javascript java rest reactjs axios
我正在尝试使用 Spring Boot/Hibernate Restful CRUD API 部署 React 项目。我在本地运行 SQL 数据库,并在开发模式 (localhost:3000) 下运行我的 React 应用程序,以便与我的 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);
});
};
Run Code Online (Sandbox Code Playgroud)
获取用户()
getUsers() {
return service.getRestClient().get("/api/getAllUsers");
}
Run Code Online (Sandbox Code Playgroud)
获取RestClient()
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;
}
Run Code Online (Sandbox Code Playgroud)
自从发帖以来,我了解到你不能在 React 的生产版本中使用代理。"proxy:"package.json 中的内容仅对开发有效,对生产无效。感谢大家的帮助。
来源:https ://create-react-app.dev/docs/proxying-api-requests-in-development/