CtrlAltDelete CtrlAltDelete - 3 months ago 7
JSON Question

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:

enter image description here

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

is the recommended way to send back a JSON-based response to the client.

Comments