React API调用开发中的工作和生产构建中的失败



我正在尝试部署一个带有Spring Boot/HHibernate 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((

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

getRestClient((

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上运行,然后你需要使用poster、高级RESTapi或失眠等工具尝试一个简单的请求。

也许,您需要释放计算机上的5000端口(防火墙(。

另一个想法是,你需要指定一些标志来使用其他请求ip/端口,在我的情况下,我使用angular,我需要一些标志:

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

最新更新