0

I have the following code in Express which redirects to views/index.html page. Now I also want to send some integers to index.html as soon as some function is executed in this code. Whats the fastest way to do this?

const app = express()

var path = __dirname + '/views/'

var router = express.Router()

app.use('/',router)

router.get('/',function(req,res)
{
    res.sendFile(path+'index.html')
}
)

app.listen(3000)
user12326
  • 11
  • 3
  • `index.html` has to load some JavaScript that asks the server for the values. – Aluan Haddad Sep 20 '20 at 11:07
  • What do you mean by "send to index.html"? Do you want to update the page dynamically or just fill some values to placeholders? – lupz Sep 20 '20 at 11:18

2 Answers2

1

Personally, I would use an "ejs" file.
Install: npm install ejs --save
Then in your index.js change your code to:

const app = express()

app.set('view engine', 'ejs'); //support ejs files

app.get('/',function(req,res) {
    res.render('index.ejs', {varableName: varablePath}) //make sure your index.ejs is in your "views" folder
});

app.listen(3000);

Then in your new ejs file use the line: <%= varableName %> to import your variables across files

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • Thank you. The variable prints nicely and I am also able to log it on console but when I try to supply it to a javascript function present inside index.ejs it always give me zero or undefined. how can I get rid of that? TIA – user12326 Sep 24 '20 at 15:40
0

You need to use templating engines like EJS/Jade to do this:

  1. First of all, add it to project, by running the below command:

    npm install ejs --save

  2. Convert the html pages to ejs pages.

  3. Use the below line in the express server app:

    app.set('view engine', 'ejs');

  4. Send the javascript variables using render method. For example:

    res.render('index', {title: "Main Page", counter: 1 });

  5. Now, in the index.ejs file read the value as below wherever required

    Counter: <%= counter %>,

kavigun
  • 2,219
  • 2
  • 14
  • 33
  • Thank you. I want to use counter variable in a javascript function in index.ejs file but counter variable is undefined. how can I get rid of this problem? TIA – user12326 Sep 24 '20 at 15:38
  • You are most welcome. Follow the above steps mentioned properly it will resolve the issue. – kavigun Sep 24 '20 at 15:41