I am using Node.js and Underscore.js. I cannot determine whether to avoid JSON data on the server side or on the client side. To underline, automatic removal of interpolated values ββis not performed with the syntax <%= someValue %> , but with <%- someValue %> , which is unlike EJS and can cause confusion. GitHub had an issue , as well as commit versions of automatic exit. But a questionable comment said:
I adhere to the general philosophy that acceleration should be made closer to your data than in the template language
So, any suggestion that when is it better to do HTML output in AJAX data? The server side helper function is used here:
var htmlEscape = function(html){ return String(html) .replace(/&(?!\w+;)/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"'); }; var xss = function(obj) { if (obj instanceof Array) { for (var i = 0; i < obj.length; i++) { obj[i] = xss(obj[i]); } } else { for(var key in obj) { // key != '_id' for mongoose doc if(obj[key] instanceof Object && !(obj[key] instanceof String) && !(obj[key] instanceof Function) && key != '_id') { obj[key] = xss(obj[key]); } else if (obj[key] instanceof String || typeof(obj[key]) == "string") { obj[key] = htmlEscape(obj[key]); } else { obj[key] = obj[key]; } } } return obj; };
Then call it when you return JSON:
res.json(xss(someData));
source share