-
-
Save timelf123/2d10ef4a53f642c3db2d1efd97d19a7e 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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