2

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!

michaeltintiuc
  • 671
  • 15
  • 31

1 Answers1

4

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) {
    // ...
});
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • @Skatebail It should be fine to use it multiple times. If `_method` is available to both, they should just set the same value to `req.method`. Unless somehow your app manages to set 2 values for `_method`. – Jonathan Lonowski Oct 13 '13 at 13:32
  • Thank You very much, both for your help and time, it is working! – michaeltintiuc Oct 13 '13 at 13:39