Giter VIP home page Giter VIP logo

method-override's Introduction

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

method-override's People

Contributors

dougwilson avatar jonathanong avatar mikaa123 avatar radagaisus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

method-override's Issues

req.body is empty when using PUT method

All is fine when using the POST method. But when using PUT , req.body is empty.
And the following code structure i wrote:

Middlleware
app.use(bodyParser.urlencoded({extended: false}));
app.use(methodOverride('_method'));

HTML form
form action="/admin/edit-product/<%= product._id%>?_method=put" enctype="multipart/form-data"

Route
router.put('/edit-product/:id',function(req, res){ console.log(req.body); });

Why make the way to override method exclusive?

AFAIK, there are at least three ways to override request method:

  1. via { X-HTTP-METHOD-OVERRIDE: PUT } header
  2. via ?_method=PUT
  3. via req.body._method

In my not so complicated application which was built with express 3, there are two ways of them involved already. And as far as I can tell, we can't ditch NO. 2 and 3 completely unless the application we are implementing is totally asynchronized with JavaScript.

So why make the way to override exclusive?

app.use() requires middleware functions

After your last update on news projects i detect this error. Actually this error first show on express/lib/application.js:209:11 but later on our server file it shows on app.use(methodOverride('X-HTTP-Method-Override')); line.

No req.body checking; do query string checking

Looking in req.body is absolutely non-standard and has a big problem where the entire request body needs to be parsed before this middleware is invoked, which doesn't make any sense. I haven't seen any other method override lib support body lookups. Really, this was just a bad decision to use req.body .i.m.o

Why not support this from GET?

It seems we could not overwrite the method with a GET request.
What if we detect in both req.body and req.query?

// req.body
    if (req.body && typeof req.body === 'object' && key in req.body) {
      method = req.body[key].toLowerCase();
      delete req.body[key];
    }

Case sensitive?

Is the header (e.g. in methodOverride('X-HTTP-Method-Override')) case sensitive?

Not really an issue / more of a question

Can anyone tell me what would be the equivalent of:

<form action="/campaigns/revive/<%= revive._id %>?_method=DELETE" method="post">
    <button>Delete</button>
</form>

in pug / jade?

Not an actual issue

I just want to thank you. You saved me a lot of time (and headaches)
I'm building a framework on top of express and this is exactly what I needed ;)
Framework is Saturnial (name suggestions accepted)
You rock!

Restrict HTTP method the override can arrive in

This module will accept the method override from any method. It should probably be restricted to only certain methods (user configurable?) like only POST (the default?). The only real purpose for this module is to allow legacy systems to make a different method call than they are capable of, and really, every client can POST and POST requests typically contain bodies, so I don't see a use-case to accept method-overrides in other methods (you can always POST with no body as well).

@jonathanong @Fishrock123 @defunctzombie thoughts?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.