Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the PUT method with Express.js

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.

like image 209
Brandon Avatar asked Sep 03 '13 21:09

Brandon


People also ask

How use Put method in express JS?

put() function routes the HTTP PUT requests to the specified path with the specified callback functions. Arguments: Path: The path for which the middleware function is invoked and can be any of: A string representing a path.

What is POST () in Express?

js POST Method. Post method facilitates you to send large amount of data because data is send in the body. Post method is secure because data is not visible in URL bar but it is not used as popularly as GET method. On the other hand GET method is more efficient and used more than POST.


2 Answers

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 express, you could write something like:

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.

like image 127
headwinds Avatar answered Sep 19 '22 21:09

headwinds


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).

like image 24
jet street Avatar answered Sep 19 '22 21:09

jet street