'webpack-dev-server - support for POST, PUT, Delete Methods using proxy
I am using webpack-dev-server as a proxy to my original API URL to avoid CORS related issues and dynamically pointing to Dev, UAT, Mock server URL based on the environments.
For Mock dev - I prefer to use the JSON from the local file system and it servers its purpose for all the GET request.
How to to add support for 'POST, PUT, DELETE' so that the local JSON can be served directly?
One possible approach may be - Overriding the HTTP Request methods to GET as I am not passing any payload. But I can't find any configuration for that.
Below is the current configuration :
if (IS_MOCK_SERVER) {
devServer.proxy = {
'/api': {
target: 'http://localhost:9090/data',
secure: false,
pathRewrite: function(req, options) {
return req + '.json'
}
}
}
} else {
devServer.proxy = {
'/api': {
target: 'http://dev-server-url.com',
secure: false
}
}
}
I tried digging into the official documents, but didn't get much support on this topic.
The Webpack dev server makes use of http-proxy-middleware to optionally proxy requests to a separate, possibly external, backend server.
Solution 1:[1]
As the Webpack dev server internally makes use of http-proxy-middleware to optionally proxy requests to other servers.
So, I opened a ticket at : https://github.com/chimurai/http-proxy-middleware/issues/151
Would be looking for a better solution in future.
But for time being, I found one workaround for the requirement/problem by Overriding the HTTP Method in API Util itself before passing it to Webpack-dev-server.
// Convert all the Request Method to Get ***ONLY IF*** MOCK-Server is running
if (process.env.IS_MOCK_SERVER) {
payload.method = 'get';
}
Solution 2:[2]
after much tinkering found this setup which i'm using to convert all requests to "GET" using the onProxyReq event in http proxy middleware. i'm using it in context of angular cli proxy setup, but will work same for any webpack dev server instance
onProxyReq: function(proxyReq, req, res) {
// convert all api requests (POST/PUT/DELETE) to GET so they work in webpack dev server for mocking
proxyReq.method = 'GET';
}
https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ravi Roshan |
Solution 2 | Dan |