Node.js - Express 4.x - method-override not handling PUT request
We could also use a simple middleware to handle x-http-method-override
var router = express.Router();
/**
* Middleware that detects a HTTP method tunneled,
* inside the header of another HTTP method. Detects
* and routs to the method mentioned in the header.
*/
router.use((req,resp,next)=>{
if(req.headers['x-http-method-override']){
req.method = req.headers['x-http-method-override'];
}
next();
});
As of method-override v2.0.0 (release 2014-06-01), the default behaviour of the middleware does not check the POST body for a _method
field; it only checks the X-HTTP-Method-Override
header.
In order for method-override to operate as it did in previous versions, you need to provide a custom function to methodOverride
, which is detailed on the project page:
custom logic
You can implement any kind of custom logic with a function for the
getter
. The following implements the logic for looking inreq.body
that was inmethod-override
1:var bodyParser = require('body-parser') var connect = require('connect') var methodOverride = require('method-override') app.use(bodyParser.urlencoded()) app.use(methodOverride(function(req, res){ if (req.body && typeof req.body === 'object' && '_method' in req.body) { // look in urlencoded POST bodies and delete it var method = req.body._method delete req.body._method return method } }))
A simpler way could be override using a query value:
var methodOverride = require('method-override')
// override with POST having ?_method=PUT
app.use(methodOverride('_method'))
Example call with query override using HTML :
<form method="POST" action="/resource?_method=PUT">
<button type="submit">Put resource</button>
</form>