0

我使用车把作为模板引擎使用 express-generator 创建了一个 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

[ {“userId”:1,“id”:1,“title”:“sunt aut facere repellat provident occaecati excepturi optio reprehenderit”,“body”:“quia et suscipit\nssuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 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" }, {.....

我在上面添加了代码,数据不会在每个循环中显示。

4

1 回答 1

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 :)
                  } 
              });


};
于 2017-10-19T16:22:50.100 回答