2

In my server, I retrieve an object from the database and have it in a variable as follows:

let files = [{"file1": "file1Data"}, {"file2": "file2Data"} ... ];

I want this data to be available in my client side JavaScript.

One way to do this would be to set up an API to call within my JavaScript. My thinking is that this would cause an extra round trip. This is because there is one request to load the initial HTML/JavaScript and then a further request to load the JSON data.

Therefore, it would be faster to send the JavaScript to the client along with the initial request that loaded the page.

How can I send a JSON object directly from the server and have it available in my client side JavaScript?

Hoa
  • 19,858
  • 28
  • 78
  • 107
  • There's a number of options. See this answer from this other SO question: https://stackoverflow.com/a/19696261/3407994 – kuanb Jul 18 '18 at 00:50
  • 2
    If you are sending a page with this request, you can include a script tag in the page and set this as a variable. – Mark Jul 18 '18 at 00:51
  • Sorry, what do you mean by 'setting up an API cause an extra round trip'..... Are you running both of your node instance and your front end webpage locally ? – user3003238 Jul 18 '18 at 00:51
  • 1
    This is a slightly different question to that link @NullPointer. I believe he's asking more about how to include JSON data alongside an HTML page in a response – Nick Abbott Jul 18 '18 at 00:55
  • I think using **JSON.stringify** to convert in string an on client side take a **hidden variable** to store this string.Later in JavaScript you can refer hidden element value – NullPointer Jul 18 '18 at 01:29

3 Answers3

2

I would use a templating engine such as EJS or Handlebars.

As an example, using EJS (http://ejs.co/) -

Server side:

// Set EJS as the view engine for Express
app.set('view engine', 'ejs');

// or just create a directory named 'views'
app.set('views', [
  path.join(__dirname, 'path/to/views'),
]);

app.get('/index', (req, res)=> {
  // 'index' must be in views dir
  return res.render('index', {
    // Pass in foo as the second argument
    // to res.render()
    foo: 'bar'
  });
})

index.ejs (EJS template):

<script>
  const foo = <%- JSON.stringify(foo) %>;
</script>
Adam Patterson
  • 958
  • 7
  • 13
1

Before serving the static files, you would need to fetch the object from the database and add the content to the files you're sending. So some kind of server-side processing. The Node app could read index.html from disk, parse it, find a place where to set the json data, and then send the data as response.

I would not do it that way though. You're already making multiple requests, e.g., client asks for index.html. Server sends that file. Client then asks for all the resources like css, JavaScript, images, fonts, etc. Another little request for some json data won't hurt.

user835611
  • 2,309
  • 2
  • 21
  • 29
1

As you said, API is the most common method if you retrieve the data from database (since you might do it after the website is loaded). If you retrieve the site when the user is requesting website, my method will be simply render it into the HTML that you serve to user.

I'm gonna show a simple sample here with pure app.write and app.get.

app.get('/', (req, res)=> {
  res.write("<h1>Hi</h1>");
  res.write("<script>var data="+ObjectYouRetrieve+";</script>");
  res.end();
})
Andrew.Wolphoe
  • 420
  • 5
  • 18