I am creating application using node.js express where i want to pass some data from express and use in external javascript file.
here is my app.js
const express=require('express');
const path=require('path');
const app=express();
const bodyParser=require('body-parser');
//configure app
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));
//use middleware
app.use(express.static(path.join(__dirname, 'bower_components')));
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//define routes
var arrayData = [
{ id: 1, desc: "Nitesh" },
{id:2,desc:"Raviaknt"}
]
app.get('/',function(req,res){
res.render('index', arrayData);
});
app.listen(800,function(){
console.log('hi');
})
here is my index.ejs file
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="bootstrap/dist/css/bootstrap.css"/>
</head>
<body>
<script src="demo.js"></script>
</body>
</html>
here is my last demo.js file
here how do i use arrayData which am passing in express
<script type='text/javascript'>var arrData =<%-JSON.stringify(arrayData)%></script>inside yourindex.ejsand see if it works.app.jsyou need to change yourapp.get('/'...)asapp.get('/',function(req,res){res.render('index',{arrayData: arrayData});});