Receive and send value with Nodejs

Asked

Viewed 850 times

0

How to receive inputs with nodejs and send a value to a given page element? 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 origin page.

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 full 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...

-Would use express, easier to use routes.

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

1 I send the 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 take the answer and enter the user name in that desired div.

I don’t know if you want to do Server Side Rendering.

Browser other questions tagged

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