Node.js - Express 4.x - 方法覆盖不处理PUT请求

时间:2014-06-03 15:47:58

标签: javascript node.js express connect

我试图让服务器处理PUT请求。但无济于事。客户端一直在接收"无法POST /"提交表单后的消息。 我正在使用Express 4.x。

请注意,如果我改变" put"到"发布"在我的路线中,请求处理得很好......

如何让我的服务器处理' PUT'请求?

服务器

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

客户端

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

5 个答案:

答案 0 :(得分:17)

更简单的方法可能是override using a query value

var methodOverride = require('method-override')

// override with POST having ?_method=PUT
app.use(methodOverride('_method'))

使用HTML进行查询覆盖的示例调用:

<form method="POST" action="/resource?_method=PUT">
  <button type="submit">Put resource</button>
</form>

答案 1 :(得分:12)

method-override v2.0.0开始(2014-06-01发布),中间件的默认行为不会检查POST主体是否为_method字段;它只检查X-HTTP-Method-Override标题。

为了使方法覆盖能够像以前的版本一样运行,您需要为methodOverride提供自定义功能,详细信息请参见the project page

  

自定义逻辑

     

您可以使用getter的函数实现任何类型的自定义逻辑。以下内容实现了查看req.body 1:

中的method-override的逻辑
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
  }
}))

答案 2 :(得分:0)

您可以选择覆盖方式:

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

答案 3 :(得分:0)

我们还可以使用简单的中间件来处理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 :(得分:0)

我刚刚开始构建我的第一个express项目,以下代码可以正常工作。来自Laravel,我希望我的路线检查_method字段的存在并确定适当的路线。所以我创建了一个中间件来做到这一点。

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;

在任何与路由相关的中间件之前使用此中间件。现在,我的表单可以像这样

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

将执行router.put('/', handler)而不是router.post('/', handler)