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?

5
  • There's a number of options. See this answer from this other SO question: stackoverflow.com/a/19696261/3407994 Commented Jul 18, 2018 at 0: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. Commented Jul 18, 2018 at 0: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 ? Commented Jul 18, 2018 at 0: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 Commented Jul 18, 2018 at 0: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 Commented Jul 18, 2018 at 1:29

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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();
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.