简体   繁体   English

如何使用EJS文件从NodeJS服务器检索完整的JSON

[英]How to retrieve full JSON from NodeJS server using EJS file

I've created a NodeJS server that sends JSON data to the front end by using an EJS file. 我创建了一个NodeJS服务器,它使用EJS文件将JSON数据发送到前端。 All I want is for the JSON code that I am taking from the three API's to be displayed on the front end (localhost). 我想要的只是我从三个API中获取的JSON代码将显示在前端(localhost)。 It works when I do something like <h1><%= data2[0]['id'] %></h1> , but that only gives me a very little piece of the JSON I need. 当我执行类似<h1><%= data2[0]['id'] %></h1> ,它可以工作,但这只能给我一小部分我需要的JSON。

Server Code: 服务器代码:

var express = require('express');
var router = express.Router();
var request = require('request');
var app = express();

router.get("/", function(req, res){
var request = require('request-promise');
var data1;
var data2;
var data3;


request("http://api1.com").then(function(body){
    data1 = JSON.parse(body);

    return request("http://api2.com");
})
    .then(function(body) {
        data2 = JSON.parse(body);


        return request("http://api3.com");
    })
    .then(function(body){
        data3 = JSON.parse(body);

        res.render("services.ejs", {data1: data1, data2: data2, data3: data3});
    })
});

module.exports = router;

Front End Example: 前端示例:

<!DOCTYPE html>
<html>
<body>

    <p><%= data1 %></p>
    <p><%= data2 %></p>
    <p><%= data3 %></p>

</body>
</html>

This is what I would want it to look like but it also could be in a paragraph or another unorganized way as long as it has the full JSON from the API: 这就是我希望它看起来像,但它也可以是一个段落或其他无组织的方式,只要它具有来自API的完整JSON:

在此输入图像描述

If you only care about displaying the data without any formatting and highlighting you can simply do 如果您只关心在没有任何格式化和突出显示的情况下显示数据,您可以这样做

res.send({data1: data1, data2: data2, data3: data3})

I'm assuming that you're seeing [object Object] or something similar with your code and even though I'm not very knowledgeable about ejs I would venture a guess that you have to traverse the object yourself and generate the relevant HTML code during the traversal. 我假设您正在看到[object Object]或与您的代码类似的内容,即使我对ejs知之甚少,我也会猜测您必须自己遍历对象并在生成过程中生成相关的HTML代码。遍历。 That way you can pretty print and highlight to your heart's content. 通过这种方式,您可以精心打印并突出显示您心中的内容。

res.json({ data1: data1, data2: data2, data3: data3 });

是推荐的向客户端发送基于JSON的响应的方法。

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

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