【发布时间】:2019-06-20 22:39:25
【问题描述】:
我正在尝试设置一个代理来处理 GET 和 POST 请求。我在之前的 react 应用程序中没有使用 react-router 已经做了很多次了,它的工作很完美,但是由于这个应用程序使用 react-router 它失败了。
代理不工作,而是尝试在 localhost 域上进行调用:
ok: false
redirected: false
status: 500
statusText: "Internal Server Error"
url: "http://localhost:3001/api/call"
我并没有对我的 react 路由器做任何花哨的事情:
<Router history={history}>
<Switch>
<Route path="/" component={Home} />
<Route path="about" component={About} />
</Switch>
</Router>
这是代理(在 setupProxy.js 中):
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/api/call', { target: "http://www.domain.com.au/", changeOrigin: true } ));
};
以下是它的使用示例:
add(data) {
this.setState({button: "loading"})
fetch('/api/call', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(res => this.setState({success: res.ok}))
.catch(err => this.setState({success: false}))
}
在使用 react-router 时,我是否需要做任何额外的工作才能完成这项工作?
【问题讨论】:
-
react-router只处理你 App 的路由部分,并根据当前路由决定应该显示哪些内容。代理是否在组件中? -
它在函数中使用,我在原问题中添加了一个示例。
-
啊,我想我可能在官方文档中找到了您的解决方案:facebook.github.io/create-react-app/docs/…
-
你能指出哪一部分可能是解决方案吗?我已阅读这些内容,但似乎找不到任何其他帮助。如前所述,这在过去非常有效,只有在使用 react-router 时才会出现问题。
-
刚看到你的回复。您可以尝试在两条路线上使用
exact参数吗? react-router 可能会干扰您的代理
标签: reactjs api proxy react-router react-router-dom