简体   繁体   中英

In Node.js/Express.js, how can I transfer a JSON object from server to client?

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?

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, eg, 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.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM