Skip to content

Instantly share code, notes, and snippets.

@bingdian
Forked from tshaddix/ngjson.js
Created March 7, 2016 03:02
Show Gist options
  • Save bingdian/9c22aaace7880af4face to your computer and use it in GitHub Desktop.
Save bingdian/9c22aaace7880af4face to your computer and use it in GitHub Desktop.
Very basic modification of Express JS res.json(). Adds the safety prefix for Angular JS to the body of all json responses. Extends the response object with one method: ngJSON. Simply require file somewhere in application (normally app.js) before executing ngJSON responses.
var http = require('http');
var NG_PREFIX = ")]}',\n";
http.ServerResponse.prototype.ngJSON = function(obj){
// allow status / body
if (2 == arguments.length) {
// res.json(body, status) backwards compat
if ('number' == typeof arguments[1]) {
this.statusCode = arguments[1];
} else {
this.statusCode = obj;
obj = arguments[1];
}
}
// settings
var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);
// content-type
this.get('Content-Type') || this.set('Content-Type', 'application/json');
return this.send(NG_PREFIX + body);
};
//e.x. res.ngJSON({ name : 'Tyler' });
//e.x. res.ngJSON(500, { error : 'Something something dark side' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment