Skip to content

Instantly share code, notes, and snippets.

@codejoust
Created August 24, 2011 18:39
Show Gist options
  • Save codejoust/1168824 to your computer and use it in GitHub Desktop.
Save codejoust/1168824 to your computer and use it in GitHub Desktop.
JSONP middleware callback.
module.exports = function(opts){
return function(req, res, next){
if ('callback' in req.query){
var callback = req.query.callback.replace(/[^A-Z0-9\.a-z_\$]/g, '');
if (callback.length == 0){
res.setHeader('X-Callback', 'Invalid');
next();
return;
}
var origHead = res.writeHead,
origEnd = res.end,
is_json = false;
res.writeHead = function(){
origHead.apply(this, arguments);
if ('content-type' in res._headers &&
res._headers['content-type'].indexOf('application/json') !== -1){
res.write(callback + '(');
is_json = true;
}
}
res.end = function(){
if (is_json){
res.write(');');
}
origEnd.apply(this, arguments);
}
}
next();
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment