How do I get webpack-dev-server to accept POST requests

丶灬走出姿态 提交于 2019-12-06 12:04:05
Kevin Beal

@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.

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.

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';
      }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!