title: ExpressJS: Response to preflight request doesn't pass access control check
body: <p>I'm running an Angular 4 (angular.io/angular cli) app on <code>http://localhost:4200</code> as well as an ExpressJS app on <code>http://localhost:3000</code></p>
  
  <h1><a href="https://github.com/AquaSolid/MEAN-stack-diversity" rel="nofollow noreferrer">ExpressJS app github link</a></h1>
  
  <h1><a href="https://github.com/AquaSolid/MEAN-stack-diversity-express" rel="nofollow noreferrer">Angular app github link</a></h1>
  
  <h2>What I've tried</h2>
  
  <p>I've spent hours on this issue, I've found a solution which is to use a chrome extension to disable CORS. 
  I've tried to add the middleware headers for CORS on my own in the ExpressJS app, because as I've read this is only a server-side issue and not a client-side one, therefore it's not angular's problem. 
  I've tried to add the <code>cors</code> npm module. That didn't work too. 
  I've deliberately added the cors lines before my routes &amp; my static folder definition in <code>app.js</code>.
  I have no idea what the issue is..</p>
  
  <h2>The error</h2>
  
  <blockquote>
    <p>Failed to load <a href="http://localhost:3000/users/post" rel="nofollow noreferrer">http://localhost:3000/users/post</a>: Response to preflight
    request doesn't pass access control check: No
    'Access-Control-Allow-Origin' header is present on the requested
    resource. Origin '<a href="http://localhost:4200" rel="nofollow noreferrer">http://localhost:4200</a>' is therefore not allowed
    access.</p>
  </blockquote>
  
  <h2>The console.log from the ExpressJS app</h2>
  
  <p><code>OPTIONS /users/post 200 1.206 ms - 13</code></p>
  
  <p>How is it 200? Why does it think that it's okay?</p>
  
  <h2>app.js</h2>
  
  <pre><code>    var express = require('express');
  var path = require('path');
  var favicon = require('serve-favicon');
  var logger = require('morgan');
  var cookieParser = require('cookie-parser');
  var bodyParser = require('body-parser');
  var app = express();
  
  // Add headers
  /*
  app.use(function (req, res, next) {
  
      // Website you wish to allow to connect
      res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
  
      // Request methods you wish to allow
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  
      // Request headers you wish to allow
      res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  
      // Set to true if you need the website to include cookies in the requests sent
      // to the API (e.g. in case you use sessions)
      res.setHeader('Access-Control-Allow-Credentials', true);
  
      // Pass to next layer of middleware
      next();
  });
  */
  
  /*var corsOptions = {
      origin: ['http://localhost:4200'],
      optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
  };
  const corsOptions = {
      origin: '*',
      method: ['GET', 'POST'],
      //allowedHeaders: ['Content-Type', 'Authorization', 'Origin', 'Accept', 'X-Requested-With'],
      optionsSuccessStatus: 200 //Some legacy browsers (IE11, various SmartTVs) choke on 204
  };
  app.use(cors(corsOptions));
  app.options('*', cors());
  */
  
  const corsOptions = {
      origin: 'http://localhost:4200',
      method: ['GET', 'POST'],
      //allowedHeaders: ['Content-Type', 'Authorization', 'Origin', 'Accept', 'X-Requested-With'],
      optionsSuccessStatus: 200 //Some legacy browsers (IE11, various SmartTVs) choke on 204,
      credentials: true
  };
  app.use(cors(corsOptions));
  
  var index = require('./routes/index');
  var users = require('./routes/users');
  
  // view engine setup
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'ejs');
  
  // uncomment after placing your favicon in /public
  //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
  app.use(logger('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({extended: false}));
  app.use(cookieParser());
  app.use(express.static(path.join(__dirname, 'public')));
  
  app.use('/', index);
  app.use('/users', users);
  
  // catch 404 and forward to error handler
  app.use(function (req, res, next) {
      var err = new Error('Not Found');
      err.status = 404;
      next(err);
  });
  
  // error handler
  app.use(function (err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};
  
      // render the error page
      res.status(err.status || 500);
      res.render('error');
  });
  
  module.exports = app;
  </code></pre>
  
  <h2>users.js</h2>
  
  <pre><code>    var express = require('express');
  var router = express.Router();
  
  var conn = require('../connect')();
  //var cors = require('cors');
  var table = "users";
  
  router.get('/', (req, res, next) =&gt; {
      var query = `SELECT * FROM ${table}`;
      console.log(query);
  
      conn.query(query, (err, result, fields) =&gt; {
          if (err) throw err;
          res.send(result);
      });
  });
  
  router.post('/post', (req, res) =&gt; {
  
      //console.log("Body: ", req.body);
      /**
       * Test Case:
       * {"user":{"name": "jack","email": "jack@gmail.com","password": "jackPass"}}
       * */
  
      var name = req.body.name;
      var email = req.body.email;
      var password = req.body.password;
  
      var query = `INSERT INTO ${table} VALUES (null, "${name}", "${email}", "${password}")`;
      console.log(query);
  
      conn.query(query, (err, result, fields) =&gt; {
          if (err) throw err;
          res.send(result);
      });
  });
  
  router.get('/:search/', (req, res, next) =&gt; {
  
      var search = req.params.search;
      var query = "";
  
      if (isNaN(search)) {
          query = `SELECT * FROM ${table} WHERE name LIKE '%${search}%'`;
      } else {
          query = `SELECT * FROM ${table} WHERE id='${search}'`;
      }
      console.log(query);
  
      conn.query(query, (err, result, fields) =&gt; {
          if (err) throw err;
          res.send(result);
      });
  });
  
  module.exports = router;
  var express = require('express');
  var router = express.Router();
  
  var conn = require('../connect')();
  //var cors = require('cors');
  var table = "users";
  
  router.get('/', (req, res, next) =&gt; {
      var query = `SELECT * FROM ${table}`;
      console.log(query);
  
      conn.query(query, (err, result, fields) =&gt; {
          if (err) throw err;
          res.send(result);
      });
  });
  
  router.post('/post', (req, res) =&gt; {
  
      //console.log("Body: ", req.body);
      /**
       * Test Case:
       * {"user":{"name": "jack","email": "jack@gmail.com","password": "jackPass"}}
       * */
  
      var name = req.body.name;
      var email = req.body.email;
      var password = req.body.password;
  
      var query = `INSERT INTO ${table} VALUES (null, "${name}", "${email}", "${password}")`;
      console.log(query);
  
      conn.query(query, (err, result, fields) =&gt; {
          if (err) throw err;
          res.send(result);
      });
  });
  
  router.get('/:search/', (req, res, next) =&gt; {
  
      var search = req.params.search;
      var query = "";
  
      if (isNaN(search)) {
          query = `SELECT * FROM ${table} WHERE name LIKE '%${search}%'`;
      } else {
          query = `SELECT * FROM ${table} WHERE id='${search}'`;
      }
      console.log(query);
  
      conn.query(query, (err, result, fields) =&gt; {
          if (err) throw err;
          res.send(result);
      });
  });
  
  module.exports = router;
  </code></pre>