Traveling Tech Guy
Traveling Tech Guy

Reputation: 27811

What's the role of the method-override middleware in Express 4?

Since the Router object in Express 4 supports:

var router = require('express').Router();
router.delete('/route', function(req, res) {
    //...
};

router.put('/route', function(req, res) {
    //...
};

What use is there for method-override middleware? Can I safely remove it from my app.js and package.json?

Upvotes: 26

Views: 15008

Answers (2)

user6184932
user6184932

Reputation:

Provides faux HTTP method support.

Pass an optional key to use when checking for a method override, otherwise defaults to _method. The original method is available via req.originalMethod.

  • String key
  • returns Function

Source

module.exports = function methodOverride(key){
  key = key || "_method";
  return function methodOverride(req, res, next) {
    var method;
    req.originalMethod = req.originalMethod || req.method;

    // req.body
    if (req.body && typeof req.body === 'object' && key in req.body) {
      method = req.body[key].toLowerCase();
      delete req.body[key];
    }

    // check X-HTTP-Method-Override
    if (req.headers['x-http-method-override']) {
      method = req.headers['x-http-method-override'].toLowerCase();
    }

    // replace
    if (supports(method)) req.method = method.toUpperCase();

    next();
  };
};

supports()

Check if node supports method.

Source

function supports(method) {
  return ~methods.indexOf(method);
}

Upvotes: 1

mscdex
mscdex

Reputation: 106696

The methodOverride() middleware is for requests from clients that only natively support simple verbs like GET and POST. So in those cases you could specify a special query field (or a hidden form field for example) that indicates the real verb to use instead of what was originally sent. That way your backend .put()/.delete()/.patch()/etc. routes don't have to change and will still work and you can accept requests from all kinds of clients.

Upvotes: 32

Related Questions