Node.js - Express 4.x - method-override not handling PUT request

有些话、适合烂在心里 提交于 2019-12-20 09:55:21

问题


I am attempting to have the server handle a PUT request. But to no avail. The client keeps receiving "Cannot POST /" message after submitting the form. I am using Express 4.x.

Note that if I change "put" to "post" in my route, the request gets handled just fine...

How can I have my server handle the 'PUT' request?

SERVER:

var express         = require("express");
var bodyParser      = require("body-parser");
var methodOverride  = require("method-override");

var app             = express();

app.use(bodyParser());
app.use(methodOverride());


app.get("/",function(req,res){
    res.render("index.ejs");
    console.log("GET received.");
});
app.put("/",function(req,res){
    console.log("PUT received: " + req.body.userName + " - " + req.body.password);
});

app.listen(1337);
console.log("Listening on 1337.");

CLIENT

<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
    </head>
    <body>
        <form action="/" method="post">
            First
            <input type="text" name="first">
            Last
            <input type="text" name="last">
            <input type="hidden" name="_method" value="put">
            <button type="submit">Submit</button>
        </form>
    </body>
</html>

回答1:


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>



回答2:


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 in req.body that was in method-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
  }
}))



回答3:


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



回答4:


You can choose how to 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



回答5:


I just started building my first express project and the following code works. Coming from Laravel, I wanted my routes to check for the presence of _method field and determine the appropriate route. So I created a middleware to do this.

import { RequestHandler } from "express";

// Updates the request method if there is a 
// "_method" field present in the request query or
// request body.
const methodOverride: RequestHandler = function (req, res, next) {

    // Set the request method to the "_method" value in query
    // or the request body. Perform a validation before setting the
    // request method.
    req.method = req.query._method || req.body._method || req.method;

    // Carry forward the request to next middleware
    return next();
};

export default methodOverride;

Use this middleware before any route related middlewares. And now, my forms can look like this

<form action="/" method="post">
    <input type="text" name="first">
    <input type="text" name="last">
    <input type="hidden" name="_method" value="put">
    <button type="submit">Submit</button>
</form>

The router.put('/', handler) will be executed instead of router.post('/', handler)



来源:https://stackoverflow.com/questions/24019489/node-js-express-4-x-method-override-not-handling-put-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!