Skip to content

Instantly share code, notes, and snippets.

@missinglink
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save missinglink/d29720e102fb072d78f4 to your computer and use it in GitHub Desktop.

Select an option

Save missinglink/d29720e102fb072d78f4 to your computer and use it in GitHub Desktop.
expressjs responders for JSON, CORS and JSONP
// 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