Skip to content

Instantly share code, notes, and snippets.

@naderio
Last active December 12, 2015 00:59
Show Gist options
  • Save naderio/4688063 to your computer and use it in GitHub Desktop.
Save naderio/4688063 to your computer and use it in GitHub Desktop.
CORS with node.js and jQuery.

Test

node hello-service.js to run service on port 8081, test with curl http://localhost:8081/ and curl -X POST -d name=John in terminal

serve -p 8080 . to run app on port 8080 (temporary static content server), test http://localhost:8080/ in browser

<!DOCTYPE html>
<html>
<head>
<title>Hello App</title>
</head>
<body>
<input id="name" autofocus placeholder="Put your name here!" />
<br>
<label id="greeting" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(function(){
var nameInput = $('#name');
var greetingOutput = $('#greeting');
nameInput.on('keyup', function(){
$.post('http://localhost:8081', { name: nameInput.val() }, function(data){
console.log(data);
greetingOutput.text(data);
});
});
});
</script>
</body>
</html>
var http = require('http');
https://gist.github.com/#var qs = require('querystring');
var server = http.createServer(function(request, response) {
var origin = "*";
if(request.method.toUpperCase() === "OPTIONS") {
response.writeHead("204", "No Content", {
"access-control-allow-origin": origin
"content-length": 0
});
return( response.end() );
}
var requestBuffer = "";
request.on("data", function(chunk) {
requestBuffer += chunk;
});
request.on("end", function() {
var name = qs.parse(requestBuffer).name || "World";
response.writeHead("200", "OK", {
"access-control-allow-origin": origin,
"content-type": "text/plain"
});
return( response.end("Hello " + name + "!") );
});
});
server.listen(8081);
console.log("Server running at http://localhost:8081/");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment