所以我想通過使用request
模塊/包從我的內部API從http調用中獲得的對象數組進行循環。到目前爲止,我可以從API中獲取數據,並在頁面上顯示完整對象。我想將其顯示在我的頁面上並使用EJS模板系統進行循環。我知道我可以使用AngularJS作爲前端的東西,但是我想看看我只能在服務器端使用多遠。AJAX調用(使用ExpressJS)後,在EJS模板中循環訪問數組的正確方法是什麼?
所以下面是我的代碼:
server.js
// Prepend /api to my apiRoutes
app.use('/api', require('./app/api'));
api.js
var Report = require('./models/report');
var express = require('express');
var apiRoutes = express.Router();
apiRoutes.route('/reports', isLoggedIn)
.get(function (req, res,next) {
// use mongoose to get all reports in the database
Report.find(function (err, reports) {
// if there is an error retrieving, send the error.
// nothing after res.send(err) will execute
if (err)
return res.send(err);
res.json(reports);
});
});
routes.js
var User = require('./models/user');
var request = require('request');
module.exports = function (app, passport) {
app.get('/reports', isLoggedIn, function (req, res) {
res.render('pages/new-report.ejs', {
user: req.user,
title:'New Report'
});
});
request({
uri:'http://localhost:2016/api/reports',
method:'GET'
}).on('data',function(data){
console.log('decoded chunk:' + data)
}).on('response',function(resp){
resp.on('data', function(data){
console.log('received:' + data.length + ' bytes of compressed data');
app.get('/timeline', isLoggedIn, function (req, res) {
res.render('pages/timeline', {
user: req.user,
title:'Timeline',
reports: data
});
});
})
});
}
reports.ejs
所以,如果我只是輸出的整個reports
對象這樣<p><%= reports %></p>
我的網頁上,一切工作正常,我得到這樣的:
[
{
"_id": "5775d396077082280df0fbb1",
"author": "57582911a2761f9c77f15528",
"dateTime": "30 June 2016 - 07:18 PM",
"picture": "",
"description": "",
"location": [
-122.46596999999997,
37.784495
],
"latitude": 37.784495,
"longitude": -122.46596999999997,
"address": "4529 California St, San Francisco, CA 94118, USA",
"contact": "John Doe",
"type": "Financial",
"__v": 0,
"updated_at": "2016-07-01T02:21:10.259Z",
"created_at": "2016-07-01T02:21:10.237Z",
"tags": [
"tag1,tag2"
]
}
]
但是,如果我嘗試通過對象循環如下所示它得到一個UNDEFINED作爲我的報告對象的返回屬性,我明顯地得到一個無限循環。
<ul class="timeline">
<% reports.forEach(function(report) { %>
<li class="timeline-yellow">
<div class="timeline-time">
<span class="date" style="text-align:left">
<%= report.type %> </span>
<span class="time" style="font-weight:700;font-size:25px;line-height:20px;text-align:left;">
<%= report.dateTime %> </span>
</div>
</li>
<% }) %>
</ul>
我曾嘗試循環的另一個變化,但我仍然不成功:
<ul class="timeline">
<% for (var i = 0; i < reports.length; i++) { %>
<li class="timeline-yellow">
<div class="timeline-time">
<span class="date" style="text-align:left">
<%= report[i].type %>
4/10/13 </span>
<span class="time" style="font-weight:700;font-size:25px;line-height:20px;text-align:left;">
<%= report[i].dateTime %> </span>
</div>
</li>
<% } %>
</ul>
第一個適合我的作品。 – Gintoki