How to configure webpack dev server using both historyApiFallback and proxying remote api requests?

I have a response application that uses react-router , so using the HTML5 history API, I tried historyApiFallback set true to serve 404 paths serving the same index.html , instead of returning an HTTP response.

This one-page application makes some requests to the remote API server, so I also need to proxy some requests to the explicit server, which I also run during development. The web response application is served on port 3000, and the API on port 3001.

So I tried:

 devServer:{ contentBase: 'src/www', //Relative directory for base of server devtool: 'eval', hot: true, //Live-reload inline: true, port: 3000, //Port Number host: 'localhost', //Change to '0.0.0.0' for external facing server historyApiFallback: true, proxy: { '^\/users|sitters|bookings': { target: 'http://127.0.0.1:3001', rewrite: function(req) { req.url = req.url.replace(/^\/api/, ''); } } } }, devtool: 'eval', output: { path: buildPath, //Path of output file filename: 'app.js' }, 

So, I want the api to be deleted on the remote server if the request path starts with /users or /sitters or /bookings , but otherwise go for historyApiFallback (serve index.html ).

Of course, currently historyApiFallback always works with an HTML file, but I also need a proxy server to work.

+5
source share
2 answers

In the express package, the intermediate stack matters.

The proxy must be configured in the webpack configuration first than historyApiFallback , here is what it should look like:

  devServer:{ contentBase: 'src/www', //Relative directory for base of server devtool: 'eval', hot: true, //Live-reload inline: true, port: 3000, //Port Number host: 'localhost', //Change to '0.0.0.0' for external facing server proxy: { '^\/users|sitters|bookings': { target: 'http://127.0.0.1:3001', rewrite: function(req) { req.url = req.url.replace(/^\/api/, ''); } } }, historyApiFallback: true }, 

Thus, of course, the proxy can be changed to any pattern or regular expression, as required by the application. In my case, this is what I need.

+7
source

I get the following solution:

 const REMOTE_URL = process.env.REMOTE_URL || 'http://localhost:8090/'; const config = { output: { publicPath: '/' }, devServer: { historyApiFallback: true, contentBase: './app', proxy: [{ context: '/api', target: REMOTE_URL, pathRewrite: { '^/api' : '/' } }] } }; 

Thus, the entire request http://locahost:port/api/ goes through the proxy and /api rewritten.

For example, http.get('/api/users') go to just /users .

Btw. The object inside the proxy is the http-proxy-middleware configuration .

+2
source

Source: https://habr.com/ru/post/1245507/


All Articles