简体   繁体   English

在node.js中一起发送JSON和HTML页面

[英]Sending JSON and HTML page together in node.js

I am sending my HTML file to the client in node.js as shown below 我将HTML文件发送到node.js中的客户端,如下所示

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

Here, index.html refers to a json file. 在这里,index.html是指一个json文件。 How can I send both together or refer the json file in the client? 如何将两者一起发送或在客户端中引用json文件?

HTTP only sends one resource at a time. HTTP一次仅发送一个资源。 If your page is requesting a JSON file, it needs to be served as a second request. 如果您的页面正在请求JSON文件,则需要将其作为第二个请求。

Alternatively, you can render HTML with a <script> block that has a variable assignment with your JSON-encoded data as a value. 或者,您可以使用<script>块呈现HTML,该块具有以JSON编码的数据作为值的变量赋值。

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: 如果您不想作为独立的HTTP请求从客户端请求JSON文件,则可以执行以下操作之一:

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: 例如,如果您的JSON文件返回一个名称和地址,则index.html可能如下所示:

<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. 然后,在渲染时,您可以将带有属性nameaddress的js对象传递给模板,而无需分别要求JSON文件。 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. 有点像以前的解决方案,但不太优雅,您可以将完整的JSON响应添加为带有script标记的对象,然后按您认为合适的方式使用它。 Try to append a block to he HEAD of index.html like this: 尝试像这样将块附加到index.html HEAD上:

<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: 您不能在单个请求中发送回两种文件,但是您可以在html中进行ajax调用以获取所需的json:

<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): 或通过模板引擎将json作为javascript对象添加到html中(如下所示的jade):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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