Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
method-override
Advanced tools
The method-override npm package allows you to use HTTP verbs such as PUT or DELETE in places where the client doesn't support it. This is particularly useful for working with forms in web applications, as HTML forms only support GET and POST methods.
Override using a query value
This feature allows you to override the HTTP method using a query parameter. For example, a POST request to /resource?_method=PUT will be treated as a PUT request.
const express = require('express');
const methodOverride = require('method-override');
const app = express();
// override with the X-HTTP-Method-Override header in the request
app.use(methodOverride('_method'));
app.post('/resource', (req, res) => {
res.send('POST request to the resource');
});
app.put('/resource', (req, res) => {
res.send('PUT request to the resource');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Override using a header
This feature allows you to override the HTTP method using a custom header. For example, a POST request with the header X-HTTP-Method-Override: PUT will be treated as a PUT request.
const express = require('express');
const methodOverride = require('method-override');
const app = express();
// override with the X-HTTP-Method-Override header in the request
app.use(methodOverride('X-HTTP-Method-Override'));
app.post('/resource', (req, res) => {
res.send('POST request to the resource');
});
app.put('/resource', (req, res) => {
res.send('PUT request to the resource');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Override using a function
This feature allows you to override the HTTP method using a custom function. The function can inspect the request and determine the method to override.
const express = require('express');
const methodOverride = require('method-override');
const app = express();
// override with a function
app.use(methodOverride((req, res) => {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
// look in urlencoded POST bodies and delete it
const method = req.body._method;
delete req.body._method;
return method;
}
}));
app.post('/resource', (req, res) => {
res.send('POST request to the resource');
});
app.put('/resource', (req, res) => {
res.send('PUT request to the resource');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
The connect package is a middleware framework for Node.js, which includes a variety of middleware functions for handling HTTP requests. It provides similar functionality to method-override through its own set of middleware options, but it is more comprehensive and includes many other features.
The body-parser package is used to parse incoming request bodies in a middleware before your handlers, available under the req.body property. While it does not directly provide method overriding, it is often used in conjunction with method-override to handle form submissions and other request bodies.
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Express itself does not include method overriding, but it is commonly used with method-override to handle HTTP methods in web applications.
Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it.
$ npm install method-override
NOTE It is very important that this module is used before any module that
needs to know the method of the request (for example, it must be used prior to
the csurf
module).
Create a new middleware function to override the req.method
property with a new
value. This value will be pulled from the provided getter
.
getter
- The getter to use to look up the overridden request method for the request. (default: X-HTTP-Method-Override
)options.methods
- The allowed methods the original request must be in to check for a method override value. (default: ['POST']
)If the found method is supported by node.js core, then req.method
will be set to
this value, as if it has originally been that value. The previous req.method
value will be stored in req.originalMethod
.
This is the method of getting the override value from the request. If a function is provided,
the req
is passed as the first argument, the `res as the second argument and the method is
expected to be returned. If a string is provided, the string is used to look up the method
with the following rules:
X-
, then it is treated as the name of a header and that header
is used for the method override. If the request contains the same header multiple times, the
first occurrence is used.This allows the specification of what methods(s) the request MUST be in in order to check for
the method override value. This defaults to only POST
methods, which is the only method the
override should arrive in. More methods may be specified here, but it may introduce security
issues and cause weird behavior when requests travel through caches. This value is an array
of methods in upper-case. null
can be specified to allow all methods.
To use a header to override the method, specify the header name
as a string argument to the methodOverride
function. To then make
the call, send a POST
request to a URL with the overridden method
as the value of that header. This method of using a header would
typically be used in conjunction with XMLHttpRequest
on implementations
that do not support the method you are trying to use.
var connect = require('connect')
var methodOverride = require('method-override')
// override with the X-HTTP-Method-Override header in the request
app.use(methodOverride('X-HTTP-Method-Override'))
Example call with header override using XMLHttpRequest
:
var xhr = new XMLHttpRequest()
xhr.onload = onload
xhr.open('post', '/resource', true)
xhr.setRequestHeader('X-HTTP-Method-Override', 'DELETE')
xhr.send()
function onload() {
alert('got response: ' + this.responseText)
}
To use a query string value to override the method, specify the query
string key as a string argument to the methodOverride
function. To
then make the call, send a POST
request to a URL with the overridden
method as the value of that query string key. This method of using a
query value would typically be used in conjunction with plain HTML
<form>
elements when trying to support legacy browsers but still use
newer methods.
var connect = require('connect')
var methodOverride = require('method-override')
// override with POST having ?_method=DELETE
app.use(methodOverride('_method'))
Example call with query override using HTML <form>
:
<form method="POST" action="/resource?_method=DELETE">
<button type="submit">Delete resource</button>
</form>
var connect = require('connect')
var methodOverride = require('method-override')
// override with different headers; last one takes precedence
app.use(methodOverride('X-HTTP-Method')) // Microsoft
app.use(methodOverride('X-HTTP-Method-Override')) // Google/GData
app.use(methodOverride('X-Method-Override')) // IBM
You can implement any kind of custom logic with a function for the getter
. The following
implements the logic for looking in req.body
that was in method-override@1
:
var bodyParser = require('body-parser')
var connect = require('connect')
var methodOverride = require('method-override')
// NOTE: when using req.body, you must fully parse the request body
// before you call methodOverride() in your middleware stack,
// otherwise req.body will not be populated.
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
}
}))
Example call with query override using HTML <form>
:
<!-- enctype must be set to the type you will parse before methodOverride() -->
<form method="POST" action="/resource" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">Delete resource</button>
</form>
The MIT License (MIT)
Copyright (c) 2014 Jonathan Ong me@jongleberry.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
Override HTTP verbs
The npm package method-override receives a total of 704,155 weekly downloads. As such, method-override popularity was classified as popular.
We found that method-override demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 6 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.