Consider the config below. By default webpack-dev-server will proxy /api/ requests to http://api.io/api/. I need to make it pass /api/ requests to http://api.io. I there any way to achieve this? I tried to look into into bypass and rewrite settings on proxyOptions but i seems that they aren't suited for this particular use case. For example, if I directly remove /api/ in bypass function it will just pass request to the next middleware in webpack-dev-server instead of requesting target.
devServer: {
port: 80,
proxy: {
'/api/*': {
host: 'api.io',
target: 'http://192.168.33.13/'
}
}
}
Use the rewrite callback:
devServer: {
port: 80,
proxy: {
'/api/*': {
host: 'api.io',
target: 'http://192.168.33.13/',
rewrite: function (req){
req.url = req.url.replace(/^\/api(.+)$/,'$1');
}
}
}
}
Or ES2015:
devServer: {
port: 80,
proxy: {
'/api/*': {
host: 'api.io',
target: 'http://192.168.33.13/',
rewrite: rewrite: req => req.url = req.url.replace(/^\/api(.+)$/,'$1')
}
}
}
I discovered this today by reading the webpack-dev-server code, I have no idea if/where it's documented. It seems to be a feature of webpack-dev-server rather than node-http-proxy itself.
Hope that solves it for you.
Alastair
Yeah, looks legit. I heard about this function but never quite understood how to work with it. I tried to return new request object from it instead on reassigning value on referenced object in place. You helped me. Thanks.
For those like me who are mislead by the current available documentation, the rewrite option in webpack-dev-server 2 beta doesn't exist anymore.
You just have to use the options from the new http-proxy-middleware : https://github.com/chimurai/http-proxy-middleware
So if you want to remove any /api in the url, just use this code :
devServer: {
port: 80,
proxy: {
'/api/*': {
host: 'api.io',
target: 'http://192.168.33.13/',
pathRewrite: {
'/api' : ''
}
}
}
}
Most helpful comment
For those like me who are mislead by the current available documentation, the rewrite option in webpack-dev-server 2 beta doesn't exist anymore.
You just have to use the options from the new http-proxy-middleware : https://github.com/chimurai/http-proxy-middleware
So if you want to remove any /api in the url, just use this code :