What is the best/most efficient way to send data from a view to a route using Nodejs and Express?

Asked

Viewed 244 times

0

I am a beginner in Nodejs and am responsible for a project in this tool. I am using the "EJS" engine to create the views. I created a form to send the information entered by the user to a route, on this route I want to process the information and return a reply to the view, but I do not know how to proceed with the implementation. Follow the view code and routes created so far.

artwork_1.ejs

<html>
  <head>
    <title>Página de Conversação</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h3><%= artwork %></h3>
    <img src="images/IMG01.jpg" alt="Imagem da Obra de Arte 1" title="Obra de Arte 1"></br>


    <form>
        <input type="text" name="question" placeholder="Pergunte-me" required />
        <button>Enviar</button>
    </form>

  </body>
</html>

index js.

const express = require('express');
const router = express.Router();


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: "Página Inicial" });
});

router.get('/artwork-1', function(req, res){
  res.render('artwork_1', { artwork: "Obra 1" });
});

module.exports = router;
  • You can use ajax, post or via link. You want to use ajax or it’s a page redirect?

1 answer

0


The simplest way to send client data to the server is by using the POST method in the html form.

<html>
  <head>
    <title>Página de Conversação</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h3><%= artwork %></h3>
    <img src="images/IMG01.jpg" alt="Imagem da Obra de Arte 1" title="Obra de Arte 1"></br>


    <form method="POST" action="/artwork-1">
        <input type="text" name="question" placeholder="Pergunte-me" required />
        <button>Enviar</button>
    </form>

  </body>
</html>

In you must add the attributes method="POST" and action="/artwork-1", that is to say that it is performing an HTTP request using the POST method and that this request will be sent to the route "/artwork-1.

The next step is to configure this route in express.

router.post('/artwork-1', function(req, res){
  //recebe os dados da requisição
  console.log(req.body.question);

  res.render('resposta', {resposta: 'a resposta da pergunta'}); 
  //ou
  res.redirect('/artwork-1?message=resposta');
});

I’ve added two examples of how you can answer.

  • It worked right. Thank you for answering!

Browser other questions tagged

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