Created
February 4, 2023 23:24
-
-
Save handymenny/bf865c9f4cdef4558527fcab0603f5ec to your computer and use it in GitHub Desktop.
Sample nodejs server with CORS headers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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