2017-10-18 147 views
-1

我使用表單生成器使用句柄作爲模板引擎來創建Web應用程序。如果我顯示來自響應的對象數組,它會顯示。但是,當我在視圖中的每個循環顯示什麼都沒有。如何顯示使用對象數組的對象的表格

/******************************** 
model file ../controllers/books.js 
*********************************/ 
var request = require('request'); 

exports.list = function(req, res, next){ 

    request.get({ url: "https://jsonplaceholder.typicode.com/posts" },  function(error, response, body) { 
       if (!error && response.statusCode == 200) { 
        res.render('index', { title: 'speed Tracker', list: body });  
        } 
       }); 


}; 
    /*********************** 
route file 
************************/ 
var express = require('express'); 
var router = express.Router(); 

var books = require('../controllers/books'); 
/* GET home page. */ 
router.get('/', books.list); 

<!-- language: lang-html --> 

         <table id="datatable" class="table table-striped table-bordered"> 
          <thead> 
           <tr> 
            <th>ID</th> 
            <th>Album Id</th> 
            <th>title</th> 
            <th>url</th> 
            <th>image</th> 
           </tr> 
          </thead> 
          {{list}} 
          <tbody> 
           {{#each list}} 
           <tr> 
            <td>{{id}}</td> 
            <td>{{userId}}</td> 
            <td>{{title}}</td> 
            <td>{{body}}</td> 
            <td></td> 
           </tr> 
           {{/each}} 
          </tbody> 
         </table> 
json of list 

[ { 「用戶id」:1, 「ID」:1, 「標題」: 「必須遵守AUT facere repellat公積金occaecati excepturi OPTIO reprehenderit」, 「身體」 : 「quia等suscipit \ nsuscipit recusandae consequuntur expedita等暨​​\ nreprehenderit molestiae UT UT quas totam \ nnostrum rerum EST AUTEM必須遵守REM eveniet architecto」 },{ 「用戶id」:1, 「ID」:2, 「title」:「qui est esse」, 「body」:「est rerum tempore vitae \ nsequi sint nihil reprehenderit dolor beatae ea dolores neque \ nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis \ nqui aperiam non debitis possimus qui neque nisi nulla「 }, {.....

我在上面添加的代碼數據不會在每個循環中顯示。

+0

通過對象的陣列的每個環是不工作 – Dhananjayan

+0

我嘗試都與此沒有這個每個循環內,但兩者失敗 – Dhananjayan

+0

我用{{#each列表}}在該代碼,** **表是一個對象數組。我需要構建表格。 – Dhananjayan

回答

0

我必須在book.js文件中將字符串轉換爲對象。我添加了下面的代碼。

var request = require('request'); 

exports.list = function(req, res, next){ 

    request.get({ url: "https://jsonplaceholder.typicode.com/posts" },  function(error, response, body) { 
       if (!error && response.statusCode == 200) { 
        res.render('index', { title: 'speed Tracker', list: JSON.parse(body) });  // add JSON.parse to convert string to object :) 
        } 
       }); 


};