Receive and send value with NodeJS

0

How to receive inputs with nodeJS and send a value to a particular element of the page? Example:

const fs = require('fs');
const http = require("http");
http.createServer((req, res)=>{
    fs.readFile('index.html',(err, data)=>{
        res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
        res.write(data);
        res.end();
    });
    let nome = recebe_nome_do_elemento_yourName_da_pagina_html.
    enviar nome para_elemento_showName+" Seja bem vindo!";
}).listen(8080);
console.log("rodando em http://localhost:8080");
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="text" name="yourName">
    <div name="showName"></div>
</body>
</html>

Remembering that if possible the value is sent to the same source page.

    
asked by anonymous 24.02.2018 / 15:31

1 answer

0
  

How to receive inputs with nodeJS? ...

Using GET request:

//requisição: http://localhost/entry/?name=Marcelo&peso=70
let url  = require("url");
let params = url.parse(req.url, true);
let name = params.query.name;
let peso = params.query.peso;
//agora voce trata o que tem de tratar com o NODEJS
  

... and send a value to a page element?

Here is the complete example:

//requisição: http://localhost:8080/replace/?name=Marcelo
const fs   = require("fs");
const http = require("http");
const url  = require("url");
http.createServer((req, res)=>{
    let params = url.parse(req.url, true);
    fs.readFile("index.html", function(err, data){
      let html = data.toString();
      html     = html.replace('<!--NAME-->', params.query.name + " olá !!!");
      res.writeHead(200, { "content-type": "text/html" });
      res.end(html);
    });
}).listen(8080);

This is my index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <!--NODEJS vai colocar o nome dentro do comentário-->
    <div><!--NAME--></div>
  </body>
</html>

If I were you ...

-Usaria express, easier to use routes.

- It would send the name, in this case, to the NodeJS and whatever you want to do inside the NodeJS return the JSON with the success message and the user name if you want. Example:

1 I send ajax to http://localhost:8080/user/insert/?name=Marcelo
2 I get {bool: true, message: 'Inserido!', data: { name: 'Marcelo' }}
3 I'm already in index.html , now just get the answer and enter the username in that desired div.

I do not know if you're looking to do Server Side Rendering .

    
24.02.2018 / 16:57