2016-07-04 8 views
8

Итак, я пытаюсь перебрать массив объектов, которые я получил от HTTP-вызова, используя мой внутренний API, используя модуль/пакет request. До сих пор я могу вернуть свои данные из API и отобразить полный объект на моей странице. Я хотел бы отобразить его на своей странице и прокрутить его, используя систему шаблонов EJS. Я знаю, что могу использовать AngularJS для работы с frontend, но мне хотелось бы узнать, как далеко я могу идти только на стороне сервера.Каков правильный способ циклического преобразования массива в шаблон EJS после вызова AJAX (с использованием ExpressJS)?

Так ниже мой код:

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" 
    ] 
    } 
] 

Но если я пытаюсь петля через объект, как показано ниже. Получает НЕ УКАЗАН как свойство возврата моего отчета объекта, и я получаю бесконечный цикл, очевидно.

<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> 
+0

первый работает для меня. – Gintoki

ответ

0

Асинхронный представляет собой модуль утилита, которая обеспечивает прямой вперед, мощные функции для работы с асинхронным JavaScript. Хотя первоначально разработан для использования с Node.js и устанавливаемым с помощью

npm install --save async

для документации, посетить http://caolan.github.io/async/

Примеры

// assuming openFiles is an array of file names and saveFile is a function 
// to save the modified contents of that file: 

async.each(openFiles, saveFile, function(err){ 
    // if any of the saves produced an error, err would equal that error 
}); 
// assuming openFiles is an array of file names 

async.each(openFiles, function(file, callback) { 

    // Perform operation on file here. 
    console.log('Processing file ' + file); 

    if(file.length > 32) { 
    console.log('This file name is too long'); 
    callback('File name too long'); 
    } else { 
    // Do work to process file here 
    console.log('File processed'); 
    callback(); 
    } 
}, function(err){ 
    // if any of the file processing produced an error, err would equal that error 
    if(err) { 
     // One of the iterations produced an error. 
     // All processing will now stop. 
     console.log('A file failed to process'); 
    } else { 
     console.log('All files have been processed successfully'); 
    } 
}); 
5

Синтаксис цикла for в ejs идеально но имя итерационного массива - сообщает, а вы как представляется, используют отчет [i] внутри итерации, который необходимо изменить как отчетов [i], которые должны работать.

reports.ejs

<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"> 
      <%= reports[i].type %> 
      4/10/13 </span> 
      <span class="time" style="font-weight:700;font-size:25px;line-height:20px;text-align:left;"> 
      <%= reports[i].dateTime %> </span> 
     </div> 
    </li> 
    <% } %> 
</ul> 

Надеется, что это помогает.