1

I want to show variable 'name' from nodejs in the html p tag with id='name'. when does the html page gets loaded?

view.html

<html>
<head>
  <title>TRY</title>
</head>
<body>
  <p id="name"></p>
</body>
  <script type="text/javascript" src="try.js"></script>
</html>

try.js

var http = require ('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
var name = "Ronish";
app.use(express.static('public'));
  document.getElementById('name').innerHTML=name;
server.listen('3030');
console.log('Listening on port 3030');
Douwe de Haan
  • 6,247
  • 1
  • 30
  • 45
Ronish
  • 35
  • 2
  • 6

1 Answers1

1

I guess you are intermixing two things ,server side js and client side js

 document.getElementById('name').innerHTML=name;

Above line will not be valid in node js because, document object is only available for browsers (client side js)

What you can do to display you variable? Try template engines like ejs

var http = require ('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
var name = "Ronish";
app.set('view engine', 'ejs');
app.use(express.static('public'));

server.listen('3030');
console.log('Listening on port 3030');

app.get("/",(req,res)=>{
res.render("index",{"value":name})

})

Then you can display them in your index.ejs file

<html>
<head>
  <title>TRY</title>
</head>
<body>
  <p id="name"><%=value %> </p>
</body>
  <script type="text/javascript" src="try.js"></script>
</html>

For Your Reference (express routing)

Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46