Skip to content

Instantly share code, notes, and snippets.

@HandyMenny
Created February 4, 2023 23:24
Show Gist options
  • Save HandyMenny/bf865c9f4cdef4558527fcab0603f5ec to your computer and use it in GitHub Desktop.
Save HandyMenny/bf865c9f4cdef4558527fcab0603f5ec to your computer and use it in GitHub Desktop.
Sample nodejs server with CORS headers
const http = require('http');
http.createServer(function (request, response) {
// Print request method and request url
console.log(request.method, request.url);
// Set CORS headers
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
// Read json body
let jsonBody = "";
request.on('readable', function () {
const stream = request.read();
if (stream != null) {
jsonBody += stream;
}
});
request.on('end', function () {
// Print jsonBody
console.log(jsonBody);
// Return status 200
response.writeHead(200);
// Return ok
response.end('ok');
});
}).listen(8080, '127.0.0.1');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment