Question

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?

Était-ce utile?

La solution

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.

Autres conseils

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);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top