• Stars
    star
    614
  • Rank 73,061 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Override HTTP verbs.

method-override

NPM Version NPM Downloads Build Status Test Coverage

Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it.

Install

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install method-override

API

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).

methodOverride(getter, options)

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.

getter

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:

  • If the string starts with 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.
  • All other strings are treated as a key in the URL query string.

options.methods

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.

Examples

override using a header

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 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'))

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)
}

override using a query value

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 express = require('express')
var methodOverride = require('method-override')
var app = express()

// 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>

multiple format support

var express = require('express')
var methodOverride = require('method-override')
var app = express()

// 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

custom logic

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 express = require('express')
var methodOverride = require('method-override')
var app = express()

// 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>

License

MIT

More Repositories

1

express

Fast, unopinionated, minimalist web framework for node.
JavaScript
63,539
star
2

multer

Node.js middleware for handling `multipart/form-data`.
JavaScript
11,285
star
3

morgan

HTTP request logger middleware for node.js
JavaScript
7,790
star
4

session

Simple session middleware for Express
JavaScript
6,163
star
5

cors

Node.js CORS middleware
JavaScript
5,961
star
6

body-parser

Node.js body parsing middleware
JavaScript
5,376
star
7

expressjs.com

HTML
5,138
star
8

compression

Node.js compression middleware
JavaScript
2,722
star
9

csurf

CSRF token middleware
2,299
star
10

cookie-parser

Parse HTTP request cookies
JavaScript
1,907
star
11

generator

Express' application generator
JavaScript
1,803
star
12

serve-static

Serve static files
JavaScript
1,368
star
13

cookie-session

Simple cookie-based session middleware
JavaScript
1,104
star
14

vhost

virtual domain hosting
JavaScript
758
star
15

serve-favicon

favicon serving middleware
JavaScript
620
star
16

response-time

Response time header for node.js
JavaScript
458
star
17

serve-index

Serve directory listings
JavaScript
435
star
18

errorhandler

Development-only error handler middleware
JavaScript
423
star
19

express-paginate

Paginate middleware
JavaScript
419
star
20

connect-multiparty

connect middleware for multiparty
JavaScript
347
star
21

express-namespace

Adds namespaced routing capabilities to Express
JavaScript
345
star
22

timeout

Request timeout middleware for Connect/Express
JavaScript
312
star
23

express-expose

Expose raw js, objects, and functions to the client-side (awesome for sharing utils, settings, current user data etc)
JavaScript
299
star
24

basic-auth-connect

Basic auth middleware for node and connect
JavaScript
129
star
25

domain-middleware

`uncaughtException` middleware for connect, base on `domain` module.
JavaScript
101
star
26

api-error-handler

Express error handlers for JSON APIs
JavaScript
100
star
27

flash

JavaScript
92
star
28

restful-router

Simple RESTful url router.
JavaScript
86
star
29

urlrouter

http url router, `connect` missing router middleware
JavaScript
59
star
30

discussions

Public discussions for the Express.js organization
55
star
31

vhostess

virtual host sub-domain mapping
JavaScript
24
star
32

connect-markdown

Auto convert markdown to html for connect.
JavaScript
20
star
33

expressjs.github.io

16
star
34

connect-rid

connect request id middleware
JavaScript
11
star
35

routification

DEPRECATED
JavaScript
10
star
36

mime-extended

DEPRECATED - Please use mime-types instead.
JavaScript
7
star
37

statusboard

A project status board for the Express community
6
star
38

.github

5
star
39

set-type

DEPRECATED - Please use mime-types instead.
JavaScript
5
star
40

security-wg

Express.js Security Working Group
4
star
41

Admin

Admin repository for the Express Organization, including pillarjs and jshttp
2
star