Javascript Express 和 ejs <%= 渲染一个 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13788314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Express and ejs <%= to render a JSON
提问by piggyback
In my index.ejs I have this code:
在我的 index.ejs 我有这个代码:
var current_user = <%= user %>
In my node I have
在我的节点中,我有
app.get("/", function(req, res){
res.locals.user = req.user
res.render("index")
})
However, on the page I obtain
但是,在我获得的页面上
var current_user = [object Object]
and if I write
如果我写
var current_user = <%= JSON.stringify(user) %>
I obtain:
我获得:
var current_user = {"__v":0,"_id":"50bc01938f164ee80b000001","agents":...
Is there a way to pass a JSON that will be JS readable?
有没有办法传递一个JS 可读的 JSON ?
回答by piggyback
Oh that was easy, don't use <%=, use <%-instead. For example:
哦,那很简单,不要使用<%=,<%-而是使用。例如:
<%- JSON.stringify(user) %>
The first one will render in HTML, the second one will render variables (as they are, eval)
第一个将在 HTML 中呈现,第二个将呈现变量(就像它们一样,eval)
回答by user732456
Attention!
注意力!
If the user can be created through API calls, <%- would leave you with serious XSS vulnerability. Possible solutions can be found here:
如果用户可以通过 API 调用创建,<%- 会给你留下严重的 XSS 漏洞。可以在此处找到可能的解决方案:

