首页 > 解决方案 > 如何将数据从节点 js 传递到 html?

问题描述

如何将数据从 node.js 传递到 html 页面?我知道有模板引擎,但它们与 express 一起使用——我在本机 nodejs 中需要它。试图这样做:

let str = ''
Post.find({}, function(err, docs) { 
    if (err) return console.log(err)
    
    for (let i in docs) {
        str += '<tr><td>' + docs[i].title + '</td><td>' + docs[i].text + '</td></tr>'
    }
});

但是如何将此变量传递str到 html 文件中的正确位置?有这样的东西:

<div class="posts">
    <table>
        str
    </table>
</div>

标签: htmlnode.js

解决方案


您必须创建唯一的字符串,例如#str#,读取文件然后替换该字符串

let str = ''
Post.find({}, function(err, docs) { 
    if (err) return console.log(err)

    for (let i in docs) {
        str += '<tr><td>' + docs[i].title + '</td><td>' + docs[i].text + '</td></tr>'
    }
    
    /*
    <div class="posts">
        <table>
          #str#
        </table>
    </div>
    */
    let template = fs.readFileSync('template.html');
    template = template.replace('#str#', str);
});

或使用cheerio html 解析器

// template.html without "str"
/*
<div class="posts">
    <table>
    </table>
</div>
*/

let template = fs.readFileSync('template.html');
const cheerio = require('cheerio');
const $ = cheerio.load(template);
$('.posts table').html(str);

推荐阅读