Skip to content

Commit

Permalink
#1240 - Allow more granular control over JSONP. Adds an options objec…
Browse files Browse the repository at this point in the history
…t to Response.json()
  • Loading branch information
daguej committed Jul 22, 2012
1 parent 54d37c6 commit f98e3e1
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,31 +96,42 @@ res.send = require('response-send');
*/

res.json = function(obj){
// allow status / body
if (2 == arguments.length) {
var options = {};
// allow status / body / options
if (arguments.length > 1) {
// res.json(body)
// res.json(status, body)
// res.json(body, status) backwards compat
// res.json(body, options)
// res.json(status, body, options)

if ('number' == typeof arguments[1]) {
this.statusCode = arguments[1];
} else {
this.statusCode = obj;
obj = arguments[1];
if ('number' == typeof obj) {
this.statusCode = obj;
obj = arguments[1];
if (arguments[2]) options = arguments[2];
} else {
if (arguments[1]) options = arguments[1];
}
}
}

// settings
var app = this.app
, jsonp = app.get('jsonp callback')
, replacer = app.get('json replacer')
, spaces = app.get('json spaces')
, replacer = options.jsonReplacer || app.get('json replacer')
, spaces = options.jsonSpaces || app.get('json spaces')
, body = JSON.stringify(obj, replacer, spaces)
, callback = this.req.query[app.get('jsonp callback name')];
, callback = this.req.query[options.jsonpCallbackName || app.get('jsonp callback name')];

// content-type
this.charset = this.charset || 'utf-8';
this.set('Content-Type', 'application/json');

// jsonp
if (callback && jsonp) {
if (callback && ((jsonp && options.jsonp !== false) || options.jsonp === true)) {
this.set('Content-Type', 'text/javascript');
body = callback.replace(/[^[]\w$.]/g, '') + '(' + body + ');';
}
Expand Down

0 comments on commit f98e3e1

Please sign in to comment.