how to proxy to backend server on certain path?

2020-08-13 02:00发布

Here is the routes config:

<Route path='/' component={CoreLayout}>
  <IndexRoute component={HomeView}/>
  <Route path='/404' component={NotFoundView}/>
  <Redirect from='*' to='/404'/>
</Route>

Here is the proxy config for webpack-dev-server:

proxy: {
  '/service': 'http://localhost:8080'
}

The express server listens on 3000 port.

I hope that all the requests send to http://localhost:3000/service would be transferred to http://localhost:8080, but it seems that react-router handles all the requests and the proxy does not work.

Any body knows how to fix this? Thank you in advance

2条回答
地球回转人心会变
2楼-- · 2020-08-13 02:08

Make sure you are handling promises correctly for the API calls. I was facing the same issue, wherein the client server was handling all the of the API calls instead of returning a 404 error and proxy taking over.

fetch("/api/list")
    .then(res => res.json())
    .then(data => {
      // handle the data
      })
查看更多
▲ chillily
3楼-- · 2020-08-13 02:23
  1. Check Webpack Dev Server documentation, you need to provide object with target property.

  2. http-proxy-middleware documentation shows usage of patterns for matching.

In conclusion, I would try this:

proxy: {
  '/service/**': { target: 'http://localhost:8080' }
}
查看更多
登录 后发表回答