Problems with Node + express routers

Asked

Viewed 54 times

0

I have a sequence of methods (get, post, put, delete), however the put method is wrong and I do not know how to solve.

this is the code snippet:

router.route('/')
    .get((req, res) => res.status(200).send('Lista de Produtos'))
    .post((req, res) => res.status(201).send(req.body))
    .put(':id',(req, res, next) => {
        const id = req.params.id;
        res.status(201).send({
            id: id,
            item: req.body
        });
    })
    .delete((req, res) => res.send('Remove Produtos'))

And this is the mistake:

Error: Route.put() requires a callback Function but got a [Object String]

I need the url to forward an id as for example : http://localhost:3000/products/123

The id would be 123..

and the answer would be { "id" means "123", "item": { } }

1 answer

0

Good afternoon Vitor,

The example I use to create CRUD’s on Node is this one, https://www.codementor.io/olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd

I suggest you take a look at how it does req.params directly and in the callback Function it puts in case of error

 exports.update_a_task = function(req, res) {
     Task.findOneAndUpdate({_id: req.params.taskId}, req.body, {new: true}, function(err, task) {
         if (err)
             res.send(err);
         res.json(task);
     });
 };

The Task.findOneAndUpdate comes from this part here

    var mongoose = require('mongoose'),
    Task = mongoose.model('Tasks');

I hope I’ve helped!

  • I understood Rodrigo Melo, this was the solution I had also come up with, but I found it a little weak because I only need to use the id in one method, so I need to add every extra line of code.. But that’s okay, it’s running and working!! I liked some utilities of the owner of the post you indicated! I will deal with it calmly. Thanks!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.