Deepak
Deepak

Reputation: 5

How to use data in external javascript file from express

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

Upvotes: 0

Views: 3170

Answers (1)

Quentin
Quentin

Reputation: 943142

You have to put it somewhere that the JavaScript can access it. (The JavaScript being external isn't particularly relevant).

At the moment, you are passing it to the template renderer and then ignoring it.

Generally, you should be passing an object to the template renderer, not an array, so you would want something more like this:

res.render('index', { myArray: arrayData });

How you then access it depends on exactly which template engine you are using.

There are several ways you could inject it into the page.

  • You could create visible data, possibly by generating a table element with associated rows and data cells.
  • You could store it in <meta> elements, or in data-* attributes.
  • You could generate a <script> element and make it a global variable.

Note that with the latter two approaches you will either be better off serialising the data to a JSON string or doing so it a pretty hard requirement for the technique to work.

You could also forget about injecting it into the page and make it available through seperate URL that just outputs it as JSON. You could then have the client side JavaScript use XMLHttpRequest or fetch to request it.

Upvotes: 3

Related Questions