简体   繁体   中英

Sending JSON and HTML page together in node.js

I am sending my HTML file to the client in node.js as shown below

app.get('/get', function(req, res) {
    res.render(index.html);
});

Here, index.html refers to a json file. How can I send both together or refer the json file in the client?

HTTP only sends one resource at a time. If your page is requesting a JSON file, it needs to be served as a second request.

Alternatively, you can render HTML with a <script> block that has a variable assignment with your JSON-encoded data as a value.

If you don't want to request the JSON file from the client as an independent HTTP request you can do one of the following:

Full server side rendering:

Use a template technology like moustache or handlebars , and try to render that data inline with the response. For example if you your JSON file returns a name and an address the index.html could look like:

<div>
  <span>Name: {{name}} </span>
  <address>Address: {{address}} </span>
<div>

Then when rendering you could pass a js object with properties name and address to the template and you wouldn't need to ask for the JSON file separately. This example follows moustache guidelines just in case I wasn't explicit enough.

Inline object

A bit like the previous solution but less elegant, you can add the full JSON response as an object with within a script tag, and then use it however you see fit. Try to append a block to he HEAD of index.html like this:

<script>
   var myObject = <contents of your JSON object>
</script>

The other possible solution was just described in another answer.

I hope this helps.

You can't send two types of files back in a single request, but you could either do an ajax call in the html to get the json you need:

<script type="text/javascript">
var json_data;
$.getJSON("URL_HERE", function(data) { json_data = data; });
</script>

or add the json to the html as a javascript object via a template engine (jade shown below):

script(type="text/javascript").
    var json_data = #{ JSON.stringify(JSON_OBJECT_HERE) }

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