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});
});
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});
});
If using Express it's not necessary to use a View Engine at all, use something like this:
This works if you previously set your application to use HTML instead of any View Engine
I have achieved this by a
http API node
request which returns required object from node object forHTML
page at client ,for eg:
API: localhost:3000/username
returns logged in user from cache by node App object .
node route file,
To pass variables from node.js to html by using the res.render() method.
Example:
I figured it out I was able to pass a variable like this
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
server.js, using express()
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.