Last active
August 29, 2015 14:04
-
-
Save missinglink/d29720e102fb072d78f4 to your computer and use it in GitHub Desktop.
expressjs responders for JSON, CORS and JSONP
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
| // send a reply that is capable of JSON, CORS and JSONP | |
| function cors( req, res, obj ){ | |
| res.header('Charset','utf8'); | |
| res.header('Access-Control-Allow-Origin', '*'); | |
| res.header('Access-Control-Allow-Methods', 'GET'); | |
| res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); | |
| res.header('Access-Control-Allow-Credentials', true); | |
| // jsonp | |
| if( req.query && req.query.callback ){ | |
| res.header('Content-type','application/javascript'); | |
| return res.send( req.query.callback + '('+ JSON.stringify( obj ) + ');' ); | |
| } | |
| // regular json | |
| res.header('Content-type','application/json'); | |
| return res.json( obj ); | |
| } | |
| // send an error | |
| function error( req, res, next, err ){ | |
| console.error( 'application error:', err ); | |
| // mask error from user (contains paths) | |
| return cors( req, res, { error: 'application error' } ); | |
| } | |
| module.exports = { | |
| cors: cors, | |
| error: error | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment