How to allow CORS with Node.js (without using Express)

No need to pass it to .writeHead(), these days you can use:

response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
response.setHeader('Access-Control-Max-Age', 2592000); // 30 days

Here's a detailed answer to add CORS without plugins: The code has been taken from here. Read about CORS Security here.

const http = require('http');
const port = 8080;

http.createServer((req, res) => {
  const headers = {
    'Access-Control-Allow-Origin': '*', /* @dev First, read about security */
    'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
    'Access-Control-Max-Age': 2592000, // 30 days
    /** add other headers as per requirement */
  };

  if (req.method === 'OPTIONS') {
    res.writeHead(204, headers);
    res.end();
    return;
  }

  if (['GET', 'POST'].indexOf(req.method) > -1) {
    res.writeHead(200, headers);
    res.end('Hello World');
    return;
  }

  res.writeHead(405, headers);
  res.end(`${req.method} is not allowed for the request.`);
}).listen(port);

You don't want to use Express but yet trying to use it's middle-ware mechanism.

if

var server = http.createServer(app).listen(3000)

then server doesn't have the .use function, the cors module was designed as a middle-ware which means you need to use Express/Connect in order to use it.

You can keep being wihtout expressjs and find different ways than using cors, for e.g see here https://gist.github.com/balupton/3696140


This is because you are requesting a not-so-simple request, meaning it needs to handle preflight request which is made as an HTTP OPTIONS request (so be sure your server is able to respond to this method). The preflight request is a way of asking permissions for the actual request, before making the actual request. The server should inspect the two headers above to verify that both the HTTP method and the requested headers are valid and accepted.