【问题标题】:Render a non-specific amount of results with express/ejs使用 express/ejs 呈现非特定数量的结果
【发布时间】:2012-11-12 04:06:09
【问题描述】:

我正在尝试创建一个基本的博客平台来帮助我熟悉 node。我使用 Express 作为框架,使用 ejs 作为渲染引擎。在我的主页上,我想显示最后十个博客。到目前为止,我有:

"use strict";
var mongo = require("mongodb")
    , server = new mongo.Server("localhost", mongo.Connection.DEFAULT_PORT, {auto_reconnect: true, safe:true})
    , mdb = new mongo.Db("blog", server)
    , querystring = require("querystring")
    , express = require('express')
    , app = express();

app.configure(function() {
    app.set('view engine', 'ejs');
});

module.exports = {
    home: function home(req, res) {
        var blogs;
        //Load blogs from db
        mdb.open(function(err, db) {
            db.collection("blogs", function(err, collection) {
                var stream = collection.find({}, {"limit": 10, "sort": {"created": -1}}).stream();
                stream.on("data", function(item) {
                    app.render('blogItem', {title: item.title, content: item.content}, function(err, html) {
                        if(err) { console.error(err);   return; }
                        blogs += html;
                    });
                });
                //Render the finished page
                stream.on("end", function() {
                    res.render('home', {title: "AwesomeBlog", content: blogs});
                    db.close();
                });
            });
        });
    }
};

ejs 文件:

home.ejs

<!DOCTYPE html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= title %>!</h1>
<%= content %>
<a href="/admin">Admin section</a>
</body>

blogItem.ejs

<h4><%= title %></h4>
<p><%= content %></p>

虽然这在技术上“有效”,但每个博客呈现的 HTML 被解释为纯文本,从而导致

AwesomeBlog!

<h4>Hi</h4> <p>test 123</p> <h4>Awesome title</h4> <p>Awesome text</p> <h4>FIRST</h4> <p>POST!</p> Admin section

在这种情况下我该如何解决这个问题?

我正在尝试做的最佳实践是什么?

【问题讨论】:

    标签: node.js express ejs


    【解决方案1】:

    这是 EJS 内置的安全功能。它阻止您的用户在您的页面中嵌入包含 javascript 漏洞 (XSS) 的 html。 (他们仍然可以在表单请求等中提交不安全的字符串,但是您的模板会对其进行转义以防止浏览器漏洞。)

    要关闭它(对于您可以信任的 HTML 内容):

    Escapes html by default with <%= code %>
    Unescaped buffering with <%- code %>
    

    只需像这样切换模板中的标签:

    <h4><%= title %></h4>
    <p><%- content %></p>
    

    【讨论】:

    • 实施一般想法修复了它,但你的细节是错误的。我需要更改home.ejs 中的内容,而不是blogItem.ejs。 (我想这部分是我的错,因为我的变量名很糟糕)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    相关资源
    最近更新 更多