[javascript] Passing a variable from node.js to html

I am trying to pass a variable from node.js to my HTML file.

app.get('/main', function(req, res) {
  var name = 'hello';
  res.render(__dirname + "/views/layouts/main.html", {name:name});
});

This question is related to javascript html node.js

The answer is


To pass variables from node.js to html by using the res.render() method.

Example:

var bodyParser = require('body-parser');
var express = require('express');
var app = express();

app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);

app.get('/', function(req, res){
    res.render('index.html',{email:data.email,password:data.password});
});

If using Express it's not necessary to use a View Engine at all, use something like this:

<h1>{{ name }} </h1>

This works if you previously set your application to use HTML instead of any View Engine


I found the possible way to write.

Server Side -

app.get('/main', function(req, res) {

  var name = 'hello';

  res.render(__dirname + "/views/layouts/main.html", {name:name});

});

Client side (main.html) -

<h1><%= name %></h1>

Other than those on the top, you can use JavaScript to fetch the details from the server. html file

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
      <div id="test">
      </div>
    <script type="text/javascript">
        let url="http://localhost:8001/test";
        fetch(url).then(response => response.json())
        .then( (result) => {
            console.log('success:', result)
            let div=document.getElementById('test');
            div.innerHTML=`title: ${result.title}<br/>message: ${result.message}`;
        })
        .catch(error => console.log('error:', error));
    </script>
  </body>
</html>

server.js

app.get('/test',(req,res)=>{
    //res.sendFile(__dirname +"/views/test.html",);
    res.json({title:"api",message:"root"});
})

app.get('/render',(req,res)=>{
    res.sendFile(__dirname +"/views/test.html");
})

The best answer i found on the stack-overflow on the said subject, it's not my answer. Found it somewhere for nearly same question...source source of answer


I have achieved this by a http API node request which returns required object from node object for HTML page at client ,

for eg: API: localhost:3000/username

returns logged in user from cache by node App object .

node route file,

app.get('/username', function(req, res) {
    res.json({ udata: req.session.user });
    });

What you can utilize is some sort of templating engine like pug (formerly jade). To enable it you should do the following:

  1. npm install --save pug - to add it to the project and package.json file
  2. app.set('view engine', 'pug'); - register it as a view engine in express
  3. create a ./views folder and add a simple .pug file like so:
html
  head
    title= title
  body
    h1= message

note that the spacing is very important!

  1. create a route that returns the processed html:
app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!'});
});

This will render an index.html page with the variables passed in node.js changed to the values you have provided. This has been taken directly from the expressjs templating engine page: http://expressjs.com/en/guide/using-template-engines.html

For more info on pug you can also check: https://github.com/pugjs/pug


With Node and HTML alone you won't be able to achieve what you intend to; it's not like using PHP, where you could do something like <title> <?php echo $custom_title; ?>, without any other stuff installed.

To do what you want using Node, you can either use something that's called a 'templating' engine (like Jade, check this out) or use some HTTP requests in Javascript to get your data from the server and use it to replace parts of the HTML with it.

Both require some extra work; it's not as plug'n'play as PHP when it comes to doing stuff like you want.


use res.json, ajax, and promises, with a nice twist of localStorage to use it anywhere, added with tokens for that rare arcade love. PS, you could use cookies, but cookies can bite on https.

webpage.js

function (idToken) {
    $.ajax({
        url: '/main',
        headers: {
            Authorization: 'Bearer ' + idToken
        },
        processData: false,
    }).done(function (data) {
        localStorage.setItem('name', data.name);
        //or whatever you want done.
    }).fail(function (jqXHR, textStatus) {
        var msg = 'Unable to fetch protected resource';
        msg += '<br>' + jqXHR.status + ' ' + jqXHR.responseText;
        if (jqXHR.status === 401) {
            msg += '<br>Your token may be expired'
        }
        displayError(msg);
    });

server.js, using express()

app.get('/main',
passport.authenticate('oauth2-jwt-bearer', { session: false }),
function (req, res) {
    getUserInfo(req) //get your information to use it.
        .then(function (userinfo) {  //return your promise
            res.json({ "name": userinfo.Name});
            //you can declare/return more vars in this res.json.
            //res.cookie('name', name); //https trouble
        })
    .error(function (e) {console.log("Error handler " + e)})
    .catch(function (e) {console.log("Catch handler " + e)});
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`