【发布时间】:2019-12-16 06:51:12
【问题描述】:
我正在尝试实现一个需要访问数据库的 React 应用程序。据我所知,这可以使用 nodejs/express 作为后端来完成。此外,我的印象是,通过在我的 react package.json 文件中添加一个代理条目,我可以将 fetch 调用的“/api”请求重定向到后端服务器。但是,我认为它不起作用。在浏览器控制台中,在 localhost:3000(这是 NPM 反应服务器)上显示 404 错误。我的后端在 5000 端口上运行。
我可以访问后端服务器的“http://localhost:5000/api”,它按设计返回 JSON。
这是我的 react package.json 文件:
{
"name": "ubwo",
"version": "0.1.0",
"private": true,
"proxy":"http://localhost:5000/api",
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-redux": "^7.1.0",
"react-router": "^5.0.1",
"react-router-dom": "^5.0.1",
"react-scripts": "3.0.1",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"resolutions": {
"browserslist": "4.6.2",
"caniuse-lite": "1.0.30000974"
}
}
这是我的“测试”React 代码。我对 fetch 不太熟悉,所以代码可能需要一些更改?:
componentDidMount() {
this.callApi()
.then(res => this.setState({ response: res.express}))
.catch(err => console.log(err));
}
callApi = async() => {
const response = await fetch('/api/cust/all',{
headers:{
"accepts":"application/json"
}
});
const customers = await response.json();
if (response.status !== 200) throw Error(customers.message);
return customers;
}
【问题讨论】:
-
你可以试试
"proxy":"http://localhost:5000"吗?我不太确定,但使用当前设置代理可能会为您的端点重定向到类似/api/api/cust/all的内容。 -
如果您尝试
npm run build并从那里开始工作,它是否有效? AFAIK react-scripts 使用 webpack-dev-server 所以你的代理最好通过devServer.proxy在你的 webpack 配置中设置(在你弹出 iirc 之前它是隐藏的)作为一个简单的修复,你可以删除代理并进行获取请求fetch('localhost:5000/api/cust/all')- 虽然一旦你把它托管在某个地方,基本 url 将从 localhost 改变。 -
代理可以正常工作,并且可以使用 CRA 进行任何自定义配置,因此可以在开发中使用“react-scripts”。无需弹出或进行任何自定义设置。如果 OP 尝试直接发出请求,他们可能会遇到 CORS 问题。
-
devserkan:如果我不能像之前的一些回复所指出的那样使用直接 URL,您知道解决方案吗?我不是想重新发明轮子。我正在使用代理,因为我在几个不同的博客上阅读了关于该主题的解决方案。如果有更好的方法,无论是开发还是生产,我都愿意接受。