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 + \"/view
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)});
});
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:
npm install --save pug
- to add it to the project and package.json fileapp.set('view engine', 'pug');
- register it as a view engine in express./views
folder and add a simple .pug
file like so:html
head
title= title
body
h1= message
note that the spacing is very important!
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.
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 figured it out I was able to pass a variable like this
<script>var name = "<%= name %>";</script>
console.log(name);