Node.js - When to do HTML output on JSON data, server or client side?

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, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;'); }; 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)); 
+4
source share
1 answer

It is always better to perform sanitation / evacuation operations on the server, as everyone can spoil your code on the client side and send data at their discretion.

There is a large node.js node-validator module that has an xss () function, as well as a group of functions to check / disinfect your data.

+1
source

All Articles