Created
August 24, 2011 18:39
-
-
Save codejoust/1168824 to your computer and use it in GitHub Desktop.
JSONP middleware callback.
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
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