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

2023-12-29

我正在尝试让服务器处理 PUT 请求。但无济于事。客户端提交表单后不断收到“Cannot POST /”消息。我正在使用 Express 4.x。

请注意,如果我将路线中的“put”更改为“post”,请求就会得到很好的处理......

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

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>

一个更简单的方法可能是使用查询值覆盖 https://github.com/expressjs/method-override#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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Node.js - Express 4.x - 方法覆盖不处理 PUT 请求 的相关文章

随机推荐