Skip to content

Instantly share code, notes, and snippets.

Created November 12, 2012 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4059663 to your computer and use it in GitHub Desktop.
Save anonymous/4059663 to your computer and use it in GitHub Desktop.
Node.js CORS demo
var http = require('http');
http.createServer(function(request, response) {
var headers = {};
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Allow-Headers"] = "Content-Type,X-Requested-With, X-PINGOTHER";
headers["Access-Control-Max-Age"] = 86400;
response.writeHead(200, headers);
var objToJson = {"response": "hello cors" };
response.write(JSON.stringify(objToJson));
response.end()
}).listen(8081)
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>CORS demo</title>
</head>
<body>
view results in the console
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script type=text/javascript>
jQuery.getJSON('http://localhost:8081', function(data) {
console.log(data);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment