问题
In my project I call:
$ webpack-dev-server --history-api-fallback
And it starts an express server (I'm assuming) available on localhost:8080.
It works great except that I want to submit a form via POST into an iframe loading my app; localhost:8080 in development and something else in production.
I don't expect to do anything with that POST data in development, but in production, it needs to be POST.
When I try to use POST however, it cannot find POST /
Is there a configuration option or some other solution that will allow me to use the webpack-dev-server? (I really don't want to have to write my own server for this).
回答1:
@cowCrazy had half of the story, but didn't show how to respond with the same response for GET in the case of POST, which is what I was looking for.
In the Webpack config, you do this:
module.exports = {
    ...,
    devServer: {
        setup(app) {
            app.post('*', (req, res) => {
                res.redirect(req.originalUrl);
            });
        },
    }
}
This will just take the POST URL and redirect with the same URL, making it a GET request.
Instead of having a server error, it will redirect with GET.
回答2:
What you are looking for is devServer. Bellow you can see my config for it. Under setup(app) you can add "almost" whatever you want:
module.exports = {
    ...,
    devServer: {
        inline: true,
        port: 3000,
        publicPath: '/',
        setup(app){
            var bodyParser = require('body-parser');    
            app.use(bodyParser.json());
            app.get("/get/some-data", function(req, res){
                console.log(req);
                res.send("GET res sent from webpack dev server")
            })
            app.post("/post/some-data", bodyParser.json(), function(req, res){
                console.log(req.body);
                res.send("POST res sent from webpack dev server")
            })
        }
    }
}
EDIT: I have pushed a minimalistic example to github if you wanna take a better look.
回答3:
Check if it solves your problem by converting the POST request to GET request:
bypass: function (req, res, proxyOptions) {
      const url = req.url;
      req.method = 'GET';
      if (url.indexOf('?') > -1) {
        return url.replace('?', '.json?');
      } else {
        return url + '.json';
      }
    }
    来源:https://stackoverflow.com/questions/47442543/how-do-i-get-webpack-dev-server-to-accept-post-requests