简体   繁体   中英

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. 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). 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.

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:

在此输入图像描述

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. That way you can pretty print and highlight to your heart's content.

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

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

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