Is it possible to add data from a node script to html?

0

I'm fairly new to node.js, but I wanted in humility to understand why a code only appears in the node's console.log and can not store some variable so I

This is the API I am using: link

    var http = require('http');

    const translate = require('google-translate-api');

    var server = http.createServer(function(req, res) {

    var url = req.url;


    translate('We did it!', {to: 'pt'}).then(res => {
      console.log(res.text);
    //=> I speak English
    console.log(res.from.language.iso);
    //=> nl



    }).catch(err => {
     console.error(err);
    });



    });

     server.listen(1337, '127.0.0.1');

     console.log('Server running at http://127.0.0.1:1337/');

However, I'm lost on how to use html :( Please someone help me or give me some alternative that can use pls.

    
asked by anonymous 05.04.2018 / 02:08

1 answer

2

As already mentioned, the node runs server-side, so it will not run inside a client-side html. Think that the Node variables are in a context separate from the javascript that will run on the front. As already mentioned, you would have to make a request to your server to fetch the data from the node side. Or, inject the variables in the HTML and then send them to the client.

Thinking about your comment about wanting to use as "<p><?php $varContendoSaidaTraduzida ?> </p>"... , I think the closest thing to that would be to use a Template Engine.

The template engine will allow you to insert chunks of code in the middle of your HTML. For example, using EJS:

<body>
  <h1> Hello world! <%= message %> </h1>
</body>

Based on what you already have, I'll give you an example using template engine and also making a call to the node (server) with Fetch. It's quite simple, actually. The first step for you would be to listen for the requests and return an html:

var http = require('http');
const translate = require('google-translate-api');
var server = http.createServer(function(req, res) {
     var url = req.url;
     //Escutando em localhost:1337/translate
     if(url ==='/translate'){
         translate('We did it!', {to: 'pt'}).then(response => {
             var translated = response.text;
             res.write('<h1>'+translated+'<h1>');
             res.end(); //end the response
         }).catch(err => {
             console.error(err);
         });
     }else{
         res.write('<h1>Not found!<h1>');
         res.end(); //end the response
     }
});
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

This will cause you to see the translated message when you access the localhost: 1337 / translate.

Now what we need to do is install the template engine and create an HTML to render as soon as we receive a request, and then send it back.

First , install EJS: npm install ejs

Now create a file named home.ejs at the same level as your app.js (or the name you gave to your server node), with the following code:

<head>
  <meta charset="UTF-8">
</head>
<body>
  <h1> Tradutor </h1>
  <p> <%= message %> </p>
  <p> <%= translation %> </p>
  <p id='test'></p>
</body>
<script>
  //chamada para /fetchdata do client-side para o server-side
  fetch('/fetchdata').then(response => {
    return response.json();
  }).then(data => {
    document.getElementById('test').innerHTML = data.example;
  }).catch(err => {
    console.log(err);
  });
</script>

Now finally change your app.js to the following:

var http = require('http');
var ejs = require('ejs');
var fs = require('fs');

const translate = require('google-translate-api');
var server = http.createServer(function(req, res) {

    var url = req.url;

    //chamada para root
    if(url ==='/'){
      res.write('<h1>Welcome!</h1>');
      res.end();
    }
    //chamada para /translate
    else if(url ==='/translate'){
       translate('We did it!', {to: 'pt'}).then(response => {
           var translated = response.text;
           //ler o arquivo home.ejs
           var html = fs.readFileSync(__dirname + '/home.ejs', 'utf8');
           //json para injetar na view
           var json = {
             message: 'Olá!',
             translation: translated
           }
           //injetar json e rendizar com ejs (template engine)
           var htmlRenderizado = ejs.render(html, json);
           //envia para o client
           res.write(htmlRenderizado);
           res.end();
         }).catch(err => {
           console.error(err);
         });
     }
     //chamada para /fetchdata
     else if(url === '/fetchdata'){
       var data = {
         example: 'Data from fetch!'
       }
       res.writeHead(200, { 'Content-Type': 'application/json' });
       res.write(JSON.stringify(data));
       res.end();
     }
     else{
        res.write('<h1>Not found!<h1>'); //write a response
        res.end(); //end the response
     }
});
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Now you have an example of how to use a Template Engine and also how to make a request from html to the node! I strongly advise you to take a look at Expressjs, it will greatly facilitate the use of the routes (which in this example is very simplified).

    
08.05.2018 / 05:58