I have a react application which uses react-router
, so it's making use of HTML5 history API, I've tried historyApiFallback
set to true
to serve 404 paths serving the same index.html
instead of returning the HTTP response.
That single page application does some requests to a remote API server, that's why I also need to proxy some requests to the express server I'm also running while developing. Web react application is served on port 3000 and API runs on port 3001.
So I've 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 what I want is hitting the remote api server if the request's path starts with either /users
or /sitters
or /bookings
but go for historyApiFallback
(serve index.html
) otherwise.
Of course right now historyApiFallback works always serving the HTML file but I'd also need the proxy to be working.
Proxy should be set up at webpack config first than historyApiFallback
, this is how 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
},
So of course proxy can be changed to any pattern or regex as an application needs it. In my case that's what I needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With