How to send information from an html form to a route? - Nodejs

Asked

Viewed 931 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 typed by the user, for a route and this route I process the information and return a reply to this html/ejs page, but I do not know how to proceed with the implementation. Follow the code below the html/ejs page and the file code referring to my application routes.

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>

    <div id="divChat">

    </div>

    <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;
  • Want to send without reloading the page or reload the page?

  • @Sergio good, the ideal is that you didn’t need to reload the page, but if that’s not possible then you can reload the page instead. Do you know any way?

  • Take a look here: https://answall.com/a/6634/129 The solution with ajax is what you need. And then use this solution here: https://answall.com/a/146751/129

  • I will test the solutions you gave me. Thank you for responding!

1 answer

-4

You’re using the right express ? use the npm install -g express -Generator ,is a module that allows you to create a basic structure for your project. Regarding the code, I redid the code that I answered to you because it did not do what you needed, Now the message is sent and returns a message. The html form:

<form method="post" action="/" >
    <input type="text" name="question" placeholder="Pergunte-me" required />
    <input type="submit" value="Enviar">
</form>

add these lines to the app.js to return a confirmation message to the site after sending the message.

app.post('/', Function(req, res) { res.send( 'Has been sent '); });

no index.js no changes needed to be made.

O retorno da mensagem

Browser other questions tagged

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