Skip to content

Instantly share code, notes, and snippets.

@voronianski
Forked from bennadel/demo.htm
Last active December 10, 2015 13:59
Show Gist options
  • Save voronianski/4444462 to your computer and use it in GitHub Desktop.
Save voronianski/4444462 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Cross-Origin Resource Sharing (CORS) test</title>
</head>
<body>
<body>
<h2>Test CORS localhost</h2>
<a href="#" class="put">PUT</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('.put').click(function(e) {
e.stopPropagation();
$.ajax({
url: 'http://localhost:8081',
type: 'PUT',
dataType: 'json',
data: JSON.stringify({ name: 'John', item: 1 }),
headers: {
'X-Locale': 'en',
'X-Version': 1
},
success: function(response) {
console.log(response);
},
error: function(err) {
console.log(err);
}
});
});
})
</script>
</body>
</html>
var http = require('http'),
app = http.createServer(handler),
port = 8081;
function handler(request, response) {
var origin = request.headers.origin;
if (request.method === 'OPTIONS') {
response.writeHead(204, {
'access-control-allow-origin': origin,
'access-control-allow-methods': 'GET, POST, PUT, DELETE, OPTIONS',
'access-control-allow-headers': 'X-Locale, X-Version' // do not forget to include all headers
});
return(response.end());
}
var requestBodyBuffer = [];
request.on('data', function (chunk) {
requestBodyBuffer.push(chunk);
});
request.on('end', function() {
var requestBody = requestBodyBuffer.join(''),
responseBody = (
'Thank You For The Cross-Domain AJAX Request:\n\n' +
'Method: ' + request.method + '\n\n' +
requestBody);
response.writeHead(200, {
'access-control-allow-origin': origin,
'access-control-allow-headers': 'X-Locale, X-Version'
});
return(response.end(responseBody));
});
}
app.listen(port);
console.log('Your server goes on localhost:' + port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment