node.js Express 不能 PUT/DELETE 方法。出了什么问题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15194237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:44:18  来源:igfitidea点击:

Express cannot PUT/DELETE method. What is going wrong?

node.jsmongodbrestexpressmongoose

提问by Daniel Tate

Ok So I have a simple node.js / express.js / mongodb app set up here with my config as follows.

好的所以我在这里设置了一个简单的 node.js / express.js / mongodb 应用程序,我的配置如下。

var express = require('express'),
    mongoose = require('mongoose');
    http = require('http');

var app = express();

    app.configure(function(){
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');

    //middleware stack
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(__dirname + "/public"));
});

mongoose.connect("mongodb://localhost/hello");

The problem lies when I try to make PUT or DELETE requests. My form is this simple

问题在于当我尝试发出 PUT 或 DELETE 请求时。我的表格就是这么简单

<form method="POST" action="/users/#{user.name}">
    <input type="hidden" name="_method" value="PUT"/>
</form>

Now my router catches the route with the express .put() method

现在我的路由器使用 express .put() 方法捕获路由

app.put('/users/:name', function(req, res) {

    var b = req.body;

    Users.update(
        { name: req.user.name },
        { name: b.name, age: b.age, email: b.email },
        function(err) {
            res.redirect('/users/'+b.name);
        });
})

When I make the request I simply get a "Cannot PUT" or "Cannot DELETE" error.

当我提出请求时,我只会收到“无法放置”或“无法删除”错误。

I have tried to make this same request via chomes RESTful client with the same result.

我试图通过 chomes RESTful 客户端发出相同的请求,结果相同。

I have read a topic witch has the same problem as me although following the comments the answers did not solve my problem.

我读过一个话题,女巫和我有同样的问题,尽管按照评论回答并没有解决我的问题。

Questions I have looked into expressjs support for method delete and put without the methodoverride

我研究了 expressjs 对方法删除和放置的支持而不使用 methodoverride 的问题

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

大多数 Web 浏览器都提供 PUT、DELETE、HEAD 等方法吗?

Along with a few others. I have also referenced the express.js and mongo documentation several times. I just cant think what could be going wrong.

与其他一些人一起。我还多次引用了 express.js 和 mongo 文档。我只是想不出哪里出了问题。

Any help is appreciated.

任何帮助表示赞赏。

采纳答案by user568109

Update

更新

As Jonathan Lonowski pointed out PUTcan also be used, so you can ignore my old answer. Getting Cannot PUTor Cannot POSTerrors, means your callback is not executing successfully. My guess is that Users.updateis failing, which is why it cannot POST or PUT. Can you check it.

正如乔纳森·洛诺夫斯基(Jonathan Lonowski)指出的那样PUT,也可以使用,因此您可以忽略我的旧答案。获取Cannot PUTCannot POST错误,意味着您的回调未成功执行。我的猜测是Users.update失败了,这就是它不能 POST 或 PUT 的原因。你能检查一下吗。

Old answer

旧答案

Try changing this line

尝试更改此行

app.put('/users/:name', function(req, res) {

to

app.post('/users/:name', function(req, res) {

since you are trying to submit the form

因为您正在尝试提交表单

回答by Jonathan Lonowski

Is the <form>you listed in a view or a staticfile under __dirname + "/public"?

<form>您是在视图下还是static文件中列出的__dirname + "/public"

Within a static file, the #{user.name}probably isn't being replaced with the user's nameand will be treated as a URL Fragment.

在静态文件中, the#{user.name}可能不会被user's替换,而是被name视为URL Fragment

The <form>will actually submit to /users/rather than /users/:namesince that's the path:

<form>实际上将提交给/users/,而不是/users/:name因为这就是path

console.log(url.parse('/users/#{user.name}'));

{ hash: '#{user.name}',
  pathname: '/users/',
  path: '/users/',
  href: '/users/#{user.name}' }

The <form>should be generated from a view if it isn't since the actionneeds to be dynamic and data-driven. With Jade and assuming useris a member of locals, that would be:

<form>应该从视图如果不是因为生成action需要是动态的和数据驱动。使用 Jade 并假设user是 的成员locals,那将是:

form(method='POST', action='/users/' + user.name)
  input(type='hidden', name='_method', value='PUT')

回答by Dan Ross

Unless there is strange magic at work, your form makes a POST request, not a PUT. If you want to PUT, I would suggest using the jQuery.ajaxfunction with a type: 'PUT'parameter, like this answer, from a form handler, see jQuery.submit. Don't forget to return falseso that the form doesn't submit twice.

除非有奇怪的魔法在起作用,否则您的表单会发出 POST 请求,而不是 PUT。如果你想 PUT,我建议使用jQuery.ajax带有type: 'PUT'参数的函数,就像这个答案一样,来自表单处理程序,请参阅jQuery.submit。不要忘记return false这样表单不会提交两次。

回答by Anthony Cantellano

If your using method override, make sure you have declared it before you use your routes. That was the problem I was having.

如果您的 using 方法覆盖,请确保在使用路由之前已声明它。这就是我遇到的问题。

回答by Usama

app.post("/movies/:id")is one solution. If you still want to use app.put("/movies/:id")then try this:

app.post("/movies/:id")是一种解决方案。如果你仍然想使用app.put("/movies/:id")然后试试这个:

  1. Install method-ovveride from npm.
  2. Require it in your app.js file.
  3. Open the form from where you wanna invoke PUT request
  4. make sure your form has the following attributes:

    action="/movies/<%= movies._id %>?_method=PUT " method="POST" >

  1. 从 npm 安装 method-override。
  2. 在您的 app.js 文件中要求它。
  3. 打开您想要调用 PUT 请求的表单
  4. 确保您的表单具有以下属性:

    action="/movies/<%= movies._id %>?_method=PUT" method="POST" >

These two solutions worked for me. If you are following REST, then use the method-ovveride else app.post() will also do the trick

这两个解决方案对我有用。如果您正在关注 REST,那么使用方法-ovveride else app.post() 也可以解决问题

回答by yaya

Change res.redirect('path')to res.redirect(303, 'path')

更改res.redirect('path')res.redirect(303, 'path')

In Putand Delete, if you want to redirect to getaddress, you should pass 303 as first parameter.(source)

Putand 中Delete,如果你想重定向到get地址,你应该传递 303 作为第一个参数。来源

回答by Soheil Rezae

one solution is to use corsmiddleware for you PUT,PATCH and DELETErequests like this in your app.jsfile like this:

一种解决方案是在您的app.js文件中为您的PUT、PATCH 和 DELETE请求使用cors中间件,如下所示:

first install the corspackage via npm :

首先通过 npm安装cors包:

npm i cors

npm i cors

then add the following code to your app.js:

然后将以下代码添加到您的 app.js 中:

const cors = require('cors')

app.use(cors())