【问题标题】:Proxy API request using React Router使用 React Router 的代理 API 请求
【发布时间】: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


【解决方案1】:

问题中的代码正在运行没有问题。当代理请求返回错误时,它将显示为来自本地主机,而不是来自代理 url。

【讨论】:

    【解决方案2】:

    我们在开发模式下使用的这个代理,它在生产构建中不起作用。如果您必须使用开发模式,您的请求是 POST http://www.domain.com.au/api/call 如果您需要将您的请求直接发送到 http://www.domain.com.au/ 然后制作您的代理

    module.exports = function(app) {
      app.use(proxy('/api', {
        target: "http://www.domain.com.au/",
        changeOrigin: true,
        pathRewrite: {
                    '^/api/': '/', // remove base path
                }
        } ));
    };
    

    现在,您可以 fetch("/api/mydata") 到GET http://www.domain.com.au/mydata

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 2021-12-29
      相关资源
      最近更新 更多