简体   繁体   English

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

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

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.问题在于当我尝试发出 PUT 或 DELETE 请求时。 My form is this simple我的表格就是这么简单

<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.我还多次引用了 express.js 和 mongo 文档。 I just cant think what could be going wrong.我只是想不出哪里出了问题。

Any help is appreciated.任何帮助表示赞赏。

Update更新

As Jonathan Lonowski pointed out PUT can also be used, so you can ignore my old answer.正如乔纳森·洛诺夫斯基(Jonathan Lonowski)指出的那样,也可以使用PUT ,因此您可以忽略我的旧答案。 Getting Cannot PUT or Cannot POST errors, means your callback is not executing successfully.出现Cannot PUTCannot POST错误,意味着您的回调没有成功执行。 My guess is that Users.update is failing, which is why it cannot POST or PUT.我的猜测是Users.update失败,这就是它不能 POST 或 PUT 的原因。 Can you check it.你能检查一下吗。

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因为您正在尝试提交表单

Is the <form> you listed in a view or a static file under __dirname + "/public" ?您在__dirname + "/public"下的视图或static文件中列出了<form>吗?

Within a static file, the #{user.name} probably isn't being replaced with the user 's name and will be treated as a URL Fragment .在静态文件中, #{user.name}可能不会被user name替换,而是会被视为URL Fragment

The <form> will actually submit to /users/ rather than /users/:name since 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 action needs to be dynamic and data-driven.如果不是,则<form>应该从视图生成,因为action需要是动态的和数据驱动的。 With Jade and assuming user is a member of locals , that would be:使用 Jade 并假设userlocals的成员,那就是:

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

Unless there is strange magic at work, your form makes a POST request, not a PUT.除非有奇怪的魔法在起作用,否则您的表单会发出 POST 请求,而不是 PUT。 If you want to PUT, I would suggest using the jQuery.ajax function with a type: 'PUT' parameter, like this answer , from a form handler, see jQuery.submit .如果你想 PUT,我建议使用带有type: 'PUT'参数的jQuery.ajax函数,就像这个答案一样,来自表单处理程序,请参阅jQuery.submit Don't forget to return false so that the form doesn't submit twice.不要忘记return false以便表单不会提交两次。

If your using method override, make sure you have declared it before you use your routes.如果您的 using 方法覆盖,请确保在使用路由之前已声明它。 That was the problem I was having.这就是我遇到的问题。

app.post("/movies/:id") is one solution. app.post("/movies/:id")是一种解决方案。 If you still want to use app.put("/movies/:id") then try this:如果你仍然想使用app.put("/movies/:id")然后试试这个:

  1. Install method-ovveride from npm.从 npm 安装 method-override。
  2. Require it in your app.js file.在你的 app.js 文件中需要它。
  3. Open the form from where you wanna invoke PUT request打开您想要调用 PUT 请求的表单
  4. make sure your form has the following attributes:确保您的表单具有以下属性:

    action="/movies/<%= movies._id %>?_method=PUT " method="POST" > 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() 也可以解决问题

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

In Put and Delete , if you want to redirect to get address, you should pass 303 as first parameter.PutDelete ,如果要重定向get地址,则应将 303 作为第一个参数传递。 ( source ) 来源

one solution is to use cors middleware for you PUT,PATCH and DELETE requests like this in your app.js file like this:一种解决方案是在您的app.js文件中为您的PUT、PATCH 和 DELETE请求使用cors中间件,如下所示:

first install the cors package via npm :首先通过 npm 安装cors包:

npm i cors

then add the following code to your app.js:然后将以下代码添加到您的 app.js 中:

const cors = require('cors')

app.use(cors())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM