2016-07-04 22 views
8

Quindi sto provando a scorrere una serie di oggetti che ho ricevuto da una chiamata http usando la mia API interna usando il modulo/pacchetto request. Finora sono riuscito a recuperare i miei dati dall'API e a VISUALIZZARE l'oggetto completo sulla mia pagina. Vorrei mostrarlo sulla mia pagina e collegarlo attraverso il sistema di template EJS. So che posso usare AngularJS per le cose di frontend, ma mi piacerebbe vedere fino a che punto posso andare solo con il lato server.Qual è il modo corretto di scorrere un array in un modello EJS dopo una chiamata AJAX (usando ExpressJS)?

Quindi sotto è il mio codice:

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
Quindi, se ho semplicemente uscita l'intero reports oggetto come questo <p><%= reports %></p> sulla mia pagina, tutto funziona bene e ottengo qualcosa di simile:

[ 
    { 
    "_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" 
    ] 
    } 
] 

Ma se provo a loop through the object come visto di seguito Ottiene UNDEFINED come proprietà di restituzione del mio oggetto e ottengo un ciclo infinito apparentemente.

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

ho provato un'altra variante del ciclo, ma io sono ancora senza successo:

<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

primo uno funziona per me. – Gintoki

risposta

0

Async è un modulo di programma di utilità che fornisce, funzioni potenti straight-forward per lavorare con JavaScript asincrono. Sebbene originariamente progettato per l'uso con Node.js e installabile tramite

npm install --save async

per la documentazione, visitare http://caolan.github.io/async/

Esempi

// 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

La sintassi per il ciclo for in ejs è perfetto ma il nome dell'array iterato è report e tu sembra utilizzare report [i] all'interno dell'iterazione, che deve essere modificato come report [i], che dovrebbe funzionare.

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> 

Spero che questo aiuti.

Problemi correlati