关注lot of great help from user Jobsamuel我在获取数据时遇到了一些困难,我试图从API调用中获取数据以显示在浏览器中:
// An express route.
app.get('/activities', function (req, res) {
if (req.user !== null) {
// User is authenticated.
getUserActivities(req.user.id, res);
} else {
// Redirect to login the user isn't authenticated.
res.redirect('/login');
}
});
// This function will make API calls to Fitbit
// using the User ID we got from the PassportJS
// authentication process.
function getUserActivities(id, res) {
// It will request from Fitbit User activities.
request('https://api.fitbit.com/1/user/'+ id +'/activities/',
function (error, response, body) {
if (!error && response.statusCode == 200) {
// If everything goes well.
return res.send(body);
} else {
// If something wrong happens.
return res.send(error);
}
}
);
}
我想在使用EJS的网页上显示body
,我尝试过这样做:<%= this.body %>
。页面在浏览器中呈现,但变量显示为undefined
。我在这做错了什么?我认为这只是一个语法问题,但我觉得好像我错过了一步。
编辑:我打电话给res.render()
的代码:
app.get('/', function(req, res){
res.render('index', { user: req.user}, {body : body});
});
app.get('/account', ensureAuthenticated, function(req, res){
res.render('account', { user: req.user });
});
app.get('/login', function(req, res){
res.render('login', { user: req.user });
});
编辑2:index.ejs
<body>
<% if (!user) { %>
<h2>Welcome! Please log in.</h2>
<% } else { %>
<!-- <h2>Hello, <%= user.displayName %>.</h2> -->
<div id="wrapper">
<div id="blank"></div>
<div id="content">
<div id="info">
Output: <%= this.body %>
</div>
</div>
</div>
<% } %>
</body>
更新:问题仍然存在。我觉得放弃这个。这里有些东西不见了,对吧?
答案 0 :(得分:1)
在渲染部分中,您只需发送一个对象,其中包含所有变量:
res.render('index', { user: req.user, body : body});
变量user
和body
将发送到模板(不 this.body
)
模板:
Output: <%= body %>
因此,在您的情况下,'/'路线需要更改为:
app.get('/', function(req, res){
res.render('index', { user: req.user}); //no need for the body variable which doesn't exist yet
});
你需要'/ activities'路径才能使用索引视图,这次是一个body变量,所以你必须使用res.render。
此外,您应该将正文或错误作为回调发送到您的函数,并执行以下所有操作:
app.get('/activities', function (req, res) {
if (req.user !== null) {
// User is authenticated.
getUserActivities(req.user.id,function(body){
res.render('index', { user: req.user, body : body}); //body will contain either body or err depending on what your function returned
});
} else {
res.redirect('/login');
}
});
function getUserActivities(id,callback) {
request('https://api.fitbit.com/1/user/'+ id +'/activities/',
function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(body);
} else {
callback(error);
}
}
);
}
res.render与res.send的解释
res.send会将原始变量转发到您的浏览器。如果需要它来浏览视图,则需要使用res.render。因此,如果您尝试通过AJAX调用查询/活动并在客户端上处理原始结果,那么使用res.send会很好。请参阅res.send和res.render
的文档