天天看点

ejs和ajax,在AJAX调用(使用ExpressJS)后,在EJS模板中循环遍历数组的正确方法是什么?...

所以我试图使用request模块/包将我从http调用使用的对象数组循环到我的内部API .到目前为止,我能够从API中获取数据并在我的页面上显示完整对象.我想在我的页面上显示它并使用EJS模板系统循环它.我知道我可以使用AngularJS作为前端的东西,但我想看看我能在多大程度上只用服务器端.

以下是我的代码:

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对象

[

{

"_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作为我的报表对象的返回属性,我显然得到一个无限循环.

我尝试过循环的另一种变体,但我仍然不成功:

  • 4/10/13