The method-override package is a Node.js module facilitating the use of HTTP verbs such as PUT or DELETE where the client doesn't traditionally support it. It lets developers override the HTTP method sent in the request header using a simple middleware setup in Express.js. This is especially useful when dealing with older browsers or HTTP clients that only support GET and POST methods.
Using method-override primarily involves setting up a middleware to override the HTTP method. The middleware function overrides the req.method
property with a new value, obtained from a specified getter
. You may choose to use a header or a query string value to indicate the override method. Here's how you include and use it in an Express.js setup:
var express = require('express')
var methodOverride = require('method-override')
var app = express()
// override with the X-HTTP-Method-Override header in the request
app.use(methodOverride('X-HTTP-Method-Override'))
You can then make a POST
request with the desired method indicated in the X-HTTP-Method-Override
header. Multiple format support is also possible, using different headers where the last one takes precedence.
The following adds an additional layer of customization, allowing for an override using the _method
key in the req.body
object:
var bodyParser = require('body-parser')
var express = require('express')
var methodOverride = require('method-override')
var app = express()
app.use(bodyParser.urlencoded())
app.use(methodOverride(function (req, res) {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
var method = req.body._method
delete req.body._method
return method
}
}))
Please note that req.body
must be fully parsed before calling methodOverride()
in your middleware stack, otherwise req.body
won't be populated.
You can find the method-override documentation on its npm page at npmjs.org/package/method-override. This includes detailed information on how to setup and use the module, options available for customization, and various examples of method overrides. Additional information can be found at the source repository at https://github.com/expressjs/method-override.