Express 和 ejs <% = 呈现 JSON

在 index.ejs 中,我有以下代码:

var current_user = <%= user %>

在我的节点里

app.get("/", function(req, res){
res.locals.user = req.user
res.render("index")
})

但是,在页面上我得到了什么

var current_user = [object Object]

如果我写

var current_user = <%= JSON.stringify(user) %>

我得到:

var current_user = {&quot;__v&quot;:0,&quot;_id&quot;:&quot;50bc01938f164ee80b000001&quot;,&quot;agents&quot;:...

有没有办法传递一个将为 JS 可读的 JSON?

77207 次浏览

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)

Attention!

If the user can be created through API calls, <%- would leave you with serious XSS vulnerability. Possible solutions can be found here:

Pass variables to JavaScript in ExpressJS

if like me your object can include an escaped character such as / or " then use this more robust solution

var current_user = <%- JSON.stringify(user).replace(/\\/g, '\\\\') %>

This will work now in Express's latest version