【发布时间】:2018-02-03 04:23:40
【问题描述】:
我刚刚开始尝试使用 node Express,并希望在我的 HTML 中显示来自 API(我用 Ruby/Sinatra 制作)的一些文本。我可以console.log() 我想要的文本,但我在将它保存到一个变量以在我的ejs 文件中调用时遇到问题。如何从调用 API 的 JSON 中获取值并将其放置在我的页面上?
这是我的代码。
这是我的主要 Js 文件。
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')
})
这是我的索引路线
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"
});
};
最后这是我的 ejs 文件
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<h1> <%= title %></h1>
<p><%= sinatra %></p>
</body>
</html>
【问题讨论】:
标签: javascript node.js api express