Use delete method with express

Asked

Viewed 1,871 times

2

Hello, I’m trying to send a value of a form (id) that will be handled by express (I don’t know the technical terms for this, if you can help me too), I’ve looked a lot but I can’t pass the id parameter in the action and I can’t access the app.delete() function. How do I pass this to my app.delete?

My form:

 <form  action=<"/produtos">  method="DELETE">
     <input id="id" type="text" name="id"/>
     <input type="submit"  value="REMOVER"/>
 </form>

My app.delete (was taking Alura’s course):

app.delete('/produtos:id', function(req, res){
    console.log(req.params.id);
    var connection = app.infra.connectionFactory();
    var ProdutosDAO = new app.infra.ProdutosDAO(connection);
    var produtoID = req.params.id;
    console.log(produtoID);
    ProdutosDAO.remove(produtoID, function(erros, resultados){
      if(erros) res.send(erros.message);
      res.send("Produto " + produtoID + " removido");
    });
  });

1 answer

3

Note that you have a syntax error in HTML, < and > the most. It should be <form action="/produtos" method="DELETE">

To make it easier use a middleware to receive these parameters in the .body request. One of the most common (formerly part of Expree.js) is the body-parser. If you don’t have it, put it on the application index, right after const app = express(); thus:

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

Then to receive in the express parameters passed by the form you can use the req.body.id thus:

app.delete('/produtos', function(req, res){
    console.log(req.body.id);
    // etc...
});
  • It hasn’t worked yet. A friend said that Forms doesn’t support methods PUT And DELETE of HTTP. I thought I’d take a route like /produtos/deletar/:id, but don’t know how to pass this id on the route.

  • @Icaroregofernandes you’re right, we only allow PUT and GET. If you do GET you can use req.query.nomeDoParametro, if you use POST you can use req.body.nomeDoParametro if you want to use by url /produtos/deletar/:id you can use req.params.id.

Browser other questions tagged

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