我可能完全误解了这一点,但我正在尝试获取 Featherjs 后端服务,该服务在本地运行 (localhost:3030/forms),以便从 create-react-app 客户端 (localhost:3000) 访问。
我已在客户端上设置 package.json 文件以包含:
{
...
"proxy": "http://localhost:3030",
...
}
...App.js 现在看起来像这样:
import React, { Component } from "react";
import "./App.css";
class App extends Component {
state = { forms: [] };
componentDidMount() {
fetch("/forms")
.then(res => res.json())
.then(forms => this.setState({ forms }));
}
render() {
return (
<div className="App">
<h1>Forms</h1>
{this.state.forms.data.map(myForm => (
<div key={myForm._id}>{myForm.package_id}</div>
))}
</div>
);
}
}
export default App;
当我在浏览器中点击 localhost:3030/forms
url 时,我得到了我期望的 JSON:
{
total: 1,
limit: 10,
skip: 0,
data: [
{
columns: "8",
datarows: [
{
age: 49,
childcount: 1,
firstname: "Darius",
gender: "m",
group: 1,
insideLegMeasurement: 144,
lastname: "Holder"
}
],
package_id: "1234",
rows: "2",
_id: "k6M3zRoDfZ0EKWBw"
}
]
}
我似乎没有收到 CORS 错误,但代理请求似乎没有被传递。相反,我收到“TypeError:无法读取未定义的属性‘map’”错误...:-(
确切地说,从 1 到 11,我有多蠢?或者,我应该做什么才能让它发挥作用?
最佳答案
当请求路径中存在 /api
时,将使用 proxy
字段中的 URL。所以 /forms
将不起作用,但是例如/api/forms
将被代理到 http://localhost:3030/api/forms
。
如果您使用的是 react-scripts@2.0.0
或更高版本,您可以添加 src/setupProxy.js
文件,并使用 根据您的喜好自定义代理>http-proxy-middleware
.
这就是您的方式,以便将您的 /forms
请求发送到 http://localhost:3030
:
// src/setupProxy.js
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/forms', { target: 'http://localhost:3030/' }));
};
关于javascript - 使用 React 的代理设置从 Featherjs 后端获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54890590/