简体   繁体   中英

Proper way to interpolate JSON in Express/Jade?

It seems like this is a solved problem in older frameworks (Django, Rails), but I can't for the life of me find a solution in Express.

A super common pattern in one-page webapps is to use template data to create html and then echo the same data as JSON to the client so that it can maintain state.

each comment as comments
  div= comment

script.
  var comments = !{JSON.stringify(comments)}

Obviously this isn't safe because a user could easily create a comment that closes the script tag and performs all kinds of nastiness. What's the proper way to deal with this then?

I've seen people claim you can get by with just

JSON.stringify(comments).replace(/<\//g, '<\/')

but that seems naive especially when working with large, forgetful teams.

Similarly, I wrote a function that html escapes recursively before stringifying, but replacing " with &quot; in every string seems like overkill and bad for data binding.

EDIT

For reference, here's Django's solution https://docs.djangoproject.com/en/dev/ref/templates/builtins/#escapejs

If I understand you correctly, you're asking how one might sanitize user input to prevent content injection attacks, XSS, etc.

There are at least three existing Express middleware packages you can take a look at for this sort of thing. express-validator has some sanitization features. It in turn uses node-validator . The current version of node-validator does not do XSS sanitization, so see express-sanitizer below.

The much-beloved helmet middleware has some XSS protection stuff that might meet some or all of your needs. If you are writing an Express app and at all concerned about security, you should definitely checkout helmet if you don't already know about it.

There is an Express middleware modulecalled express-sanitizer . It appears to be recent and only have one contributor, so check the code to see if it meets your needs and seems mature. But it is trying to do XSS sanitization now that node-validator does not do that anymore. (See express-validator above.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM