How to redirect to another route and pass variables in the process? Node + Express

Asked

Viewed 465 times

1

I would like to redirect using res.redirect() so that the URL is also changed, but I’m not being able to send information in the process, could anyone tell me how to do that? I want to send together the variable "func", which contains the id of the selected employee, and in the route "editarFunctioning", render the page with the user information that will be changed.

app.post('/funcionarios', function(req, res){
let botao = req.body.botao;
let func = req.body.id;

if (botao == "Editar"){
    res.redirect('/editarFuncionario');
}...

app.get('/editarFuncionario', function(req, res){
  let query = db.query("SELECT * FROM funcionarios WHERE id = ?", [func], function(err, results){
            if (err) throw err;
           res.render('editarFuncionario', {lista:results});
        })
  
});

1 answer

0

The .redirect is used to redirect the response, not the request (request). You have to do this by calling in internal functions. That is instead of the logic of redirecting you must, within that if have the logic of the database you have in the question.

You can do this in the same file (as in the example below) or by importing functions from other files and calling them inside the if.

Example:

app.post('/funcionarios', function(req, res) {
  let botao = req.body.botao;
  let func = req.body.id;

  if (botao == "Editar") {
    db.query("SELECT * FROM funcionarios WHERE id = ?", [func], function(err, results) {
      if (err) throw err;
      res.render('editarFuncionario', {
        lista: results
      });
    })
  } else {
    // outra query com outra resposta
  }
});
  • So, I had done it this way before, but the URL remains unchanged, and by clicking the "submit" button, to perform the employee data change, the redirect is done to the URL responsible for listing the employees, since the render does not change the URL. You could do it somehow?

  • I was able to solve the problem, just take the declaration "Let" behind the variable, so I can access it in any other function, thanks for helping!

Browser other questions tagged

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