I've just started experimenting with node Express and wanted to display some text from an API (that I made in Ruby/Sinatra) in my HTML. I can console.log() the text I want, but I'm having problems saving it to a variable to call in my ejs files. How do I take a value from JSON that I got my calling my API and place it on my page?
Here is my code.
Here is my main Js file.
var express = require('express');
var app = express();
var routes = require('./routes');
app.set('view engine', 'ejs');
app.get('/', routes.index);
app.get('/about', routes.about);
var server = app.listen(3000, function() {
console.log('look at port 3000')
})
Here is my Index Route
var request = require('request');
var resq = request("http://ancient-falls-7604.herokuapp.com/users/1/posts", function(error, response, body) {
console.log (JSON.parse(body)["user_posts"][1]["post"]["body"])
})
// this thing I just console.logged is what I want saved to a var
exports.index = function(req, res){
res.render('main', {
title: 'Some Random Title',
sinatra: "JSON CALL WILL EVENTUALLY GO"
});
};
and finally here is my ejs file
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<h1> <%= title %></h1>
<p><%= sinatra %></p>
</body>
</html>
Just make your request inside your index method, save it to your variables and call render:
exports.index = function(req, res){
request("http://ancient-falls-7604.herokuapp.com/users/1/posts", function(error, response, body) {
var json = JSON.parse(body);
res.render('main', {
title: json.user_posts[0].post.title,
sinatra: json.user_posts[0].post.body
});
});
};
To make that work, make sure the name of your view file is main.ejs, since you are calling main in the render method.