Fix CORS errors on local node server

When hacking together a quick throwaway node server, it’s easy to get caught going around in circles with Cross Origin Resource Sharing and Access Control Allow Origin.

Here’s a quick and easy way to disable this so you can keep moving.

I’m using node’s http package via http.createServer.

const http = require('http');

const requestHandler = (request, response) => {
    let chunks = [];

      const headers = {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
          'Access-Control-Max-Age': 2592000, // 30 days
          "content-Type": "application/json"
          /** add other headers as per requirement */
      };
      response.writeHead(200, headers);
// do other stuff, output JSON.
response.end(JSON.stringify(obj));

function startServer() {
    let server;

    server = http.createServer(requestHandler);
    let port = 3000;
    server.listen(port, (err) => {
        if(err){
        console.log(err);

        }
          console.log(`server is listening.`);
    })
}

startServer();