Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

<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

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.

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

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

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.

Any help is appreciated.

like image 350
Daniel Tate Avatar asked Mar 04 '13 03:03

Daniel Tate


1 Answers

Update

As Jonathan Lonowski pointed out PUT can also be used, so you can ignore my old answer. Getting Cannot PUT or Cannot POST errors, means your callback is not executing successfully. My guess is that Users.update is failing, which is why it cannot POST or 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

like image 140
user568109 Avatar answered Oct 19 '22 23:10

user568109