Search code examples
javascriptformsnode.jsexpressx-http-method-override

Nodejs Express - methodOverride not working for multipart/form-data


I've noticed that if I submit a form with enctype="multipart/form-data" that has a hidden _method input set to PUT the methodOverride function will not fire, resulting in a 404 POST for that route.

The set up:

app.use(express.json());
app.use(express.urlencode());
...
app.use(express.methodOverride());
app.use(express.router());

app.put('/update', express.multipart(), function(req, res) { ... });

if i change put to post in the router everything works just fine. Also put and delete work in other routes that do not have enctype="multipart/form-data" sent to them.

I tried changing the order of the middleware but no luck with that.

Any help would be highly appreciated, since googling this issue resulted in nothing!

Thanks in advance!


Solution

  • For methodOverride() to be able to use the value of _method, it needs req.body to already have been defined by 1 of the 3 body parsers -- json(), urlencoded(), and multipart().

    app.use(express.multipart());
    app.use(express.methodOverride());
    

    If you want to use multipart() with methodOverride() for select routes, you can use an app.all() route with both middleware and call next('route') so it continues to the intended route.

    app.all('/update',
        express.multipart(),
        express.methodOverride(),
        function (req, res, next) { next('route'); }
    );
    
    app.put('/update', function (req, res) {
        // ...
    });