NodeJS检索JSON并投放到EJS模板 [英] NodeJS retrieve JSON and serve to EJS template

查看:51
本文介绍了NodeJS检索JSON并投放到EJS模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目的是获取JSON并将其提供给EJS文件.

my purpose is to get a JSON and serve it to an EJS file.

这是我的代码:

//server.js

users = require('./controllers/users.js');

global.app_root = path.resolve(__dirname);

app.get('/users', function(req, res) {
    res.render('partials/users', {
        data: users.retrieve_users
    });
})

//users.js

var fs = require("fs");

exports.retrieve_users = function (req, res) {
   fs.readFile(app_root + "/config/" + "users-list.json", 'utf8', function (err, data) {
      res.end(data);
   });
}

//users.ejs

<body>
   <%= data %>
</body>

但是作为该代码在体内的输出,我从字面上看到了这个字符串:

But as output of this code inside the body I see literally this string:

'function (req, res) {
   fs.readFile(app_root + "/config/" + "users-list.json", 'utf8', function (err, data) {
      res.end(data);
   });
}'

推荐答案

问题是您的数据即将异步,您无需等待渲染就可以了.实际上,现在您甚至都没有运行 users.retrieve_users 函数,您只需取回函数声明并将express呈现为字符串即可!将您的代码更改为此.

The problem is that your data is coming asynchronous and you don't wait for them before the rendering. In fact right now you dont even run the users.retrieve_users function, you just getting back the function declaration and express renders it as string! Change your code to this.

//server.js

users = require('./controllers/users.js');

global.app_root = path.resolve(__dirname);

app.get('/users', function(req, res) {
   
    //a method that get thr user-list data and renders it
    users.retrieve_users()
      .then(function(users){
         res.render('partials/users', {
            data: users
        });
      })
      .catch(function(err){
         res.status(500).send({ error: 'something blew up' });
      })
    
})

//users.js

var fs = require("fs");

exports.retrieve_users = function () {
   //function that returns user-list in promise
   return new Promise(function(resolve,reject){
       fs.readFile(app_root + "/config/" + "users-list.json", 'utf8', function (err, data) {
          if(err) return reject(err)
          resolve(data);
       });
   })
  
}

//users.ejs

<body>
   <%= data %>
</body>

这篇关于NodeJS检索JSON并投放到EJS模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆