Skip to content

Instantly share code, notes, and snippets.

@coderoshi
Created April 25, 2012 17:18
Show Gist options
  • Save coderoshi/2491436 to your computer and use it in GitHub Desktop.
Save coderoshi/2491436 to your computer and use it in GitHub Desktop.
CORS NodeJS Middleware
exports.cors = (req, res)->
origin = (req.headers.origin || "*")
if req.method.toUpperCase() == 'OPTIONS'
res.writeHead 200,
'Access-Control-Allow-Origin': origin
'Access-Control-Allow-Credentials': true
'Access-Control-Allow-Methods': '*'
'Access-Control-Allow-Headers': 'Accept, Authorization, Cache-Control, Content-Type, Origin, Referer, User-Agent, X-CSRF-Token'
'Content-Type': 'text/plain'
'Server': 'jsonapi'
'Content-Length': 2
res.end('ok')
true
else
res.setHeader 'Access-Control-Allow-Origin', origin
res.setHeader 'Access-Control-Allow-Methods', '*'
res.setHeader 'Access-Control-Allow-Headers', 'Content-Type'
false
http = require('http')
cors = require('./cors')
server = http.createServer()
server.on 'request', (req, res)->
return if cors.cors(req, res)
res.end("Hello Werld")
server.listen(3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment