Express and ejs <%= to render a JSON

后端 未结 3 1845
南笙
南笙 2020-12-01 01:14

In my index.ejs I have this code:

var current_user = <%= user %>

In my node I have

app.get(\"/\", function(req, res){         


        
相关标签:
3条回答
  • 2020-12-01 01:36

    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)

    0 讨论(0)
  • 2020-12-01 01:56

    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

    0 讨论(0)
  • 2020-12-01 01:56

    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, '\\\\') %>
    
    0 讨论(0)
提交回复
热议问题