24

I'm trying to implement update functionality to an Express.js app, and I'd like to use a PUT request to send the new data, but I keep getting errors using PUT. From everything I've read, it's just a matter of using app.put, but that isn't working. I've got the following in my routes file:

send = function(req, res) { 
    req.send(res.locals.content);
};

app.put('/api/:company', function(res,req) {
    res.send('this is an update');
}, send);

When I use postman to make a PUT request, I get a "cannot PUT /api/petshop" as an error. I don't understand why I can't PUT, or what's going wrong.

Brandon
  • 3,573
  • 6
  • 19
  • 21

4 Answers4

22

You may be lacking the actual update function. You have the put path returning the result back to the client but missing the part when you tell the database to update the data.

If you're using MongoDB and ExpressJS, you could write something like this :

app.put('/api/:company', function (req, res) {
    var company = req.company;
    company = _.extend(company, req.body);
    company.save(function(err) {
    if (err) {
        return res.send('/company', {
            errors: err.errors,
            company: company
        });
    } else {
        res.jsonp(company);
    }   
  })
});

This mean stack project may help you as it covers this CRUD functionality which I just used here swapping their articles for your companies. same same.

Maoz Zadok
  • 4,871
  • 3
  • 33
  • 43
headwinds
  • 1,781
  • 15
  • 26
5

Your callback function has the arguments in the wrong order.

Change the order of callback to function(req, res). Don't use function(res, req).

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
jet street
  • 51
  • 1
  • 2
0

Also if you want to redirect in put or delete (to get adress), you can't use normal res.redirect('/path'), you should use res.redirect(303, '/path') instead. (source)

If not, you'll get Cannot PUT error.

yaya
  • 7,675
  • 1
  • 39
  • 38
-6

Have you been checking out your headers information? Because header should be header['content-type'] = 'application/json'; then only you will get the update object in server side (node-express), otherwise if you have content type plain 'text/htm' like that you will get empty req.body in your node app.

MarvMan
  • 41
  • 9
selvaraj
  • 5
  • 1