Permalink
Browse files

#1240 - Allow more granular control over JSONP. Adds an options objec…

…t to Response.json()
  • Loading branch information...
1 parent 54d37c6 commit f98e3e16abf1b8f39e8e705d1ba0bbca3350f565 @daguej daguej committed Jul 22, 2012
Showing with 19 additions and 8 deletions.
  1. +19 −8 lib/response.js
View
@@ -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 + ');';
}

0 comments on commit f98e3e1

Please sign in to comment.