title: ExpressJS Post Method - No Access-Control-Allow-Origin
body: <p>I have been reading all the articles that I found about CORS but I'm still not able to solve this issue - No 'Access-Control-Allow-Origin'.</p>
  
  <p>I need to make a <strong>post request</strong> to my node/expressjs server using jquery ajax but I can't get it working.</p>
  
  <p>This is my ajax code:</p>
  
  <pre><code>$.ajax({
      url: 'http://mydevserver:3000/api/nnnn',
      type: "POST",
      data: data,
      contentType: "application/json",
      async: true,
      success: function(data) {
          console.log("success!");
      }
  });
  </code></pre>
  
  <p>And this the expressJS part where I set the response headers:</p>
  
  <pre><code>var corsOrigin  ;
  
  if (process.env.NODE_ENV == 'production') {
     console.log('Adding CORS to the headers...');
     corsOrigin = 'myprodserver';
  }
  else {
    corsOrigin = 'http://mydevserver:4200';
  }
  
  
  app.use(function(req, res, next) {
    res.set("Access-Control-Allow-Origin", corsOrigin);
    res.set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.set('Access-Control-Allow-Methods', 'POST, GET, PUT, PATCH, DELETE, OPTIONS');
  
    next();
  
  });
  </code></pre>
  
  <p>What am I missing here? I ran out of options... </p>
  
  <p>Thanks very much for the help!</p>
  
  <p>My best regards.</p>
  
  <p><strong>Update 1 - Full server and route codes</strong></p>
  
  <p>server.js</p>
  
  <pre><code>var http = require('http');
  var app = require('./app');
  
  /**
   * Get port from environment and store in Express.
   */
  
  console.log('Server port set to ' + process.env.NODE_PORT);
  var port = normalizePort(process.env.NODE_PORT || '3000');
  app.set('port', port);
  
  /**
   * Create HTTP server.
   */
  
  var server = http.createServer(app);
  
  /**
   * Listen on provided port, on all network interfaces.
   */
  
  server.listen(port);
  server.on('error', onError);
  server.on('listening', onListening);
  
  /**
   * Normalize a port into a number, string, or false.
   */
  
  function normalizePort(val) {
      var port = parseInt(val, 10);
  
      if (isNaN(port)) {
          // named pipe
          return val;
      }
  
      if (port &gt;= 0) {
          // port number
          return port;
      }
  
      return false;
  }
  
  /**
   * Event listener for HTTP server "error" event.
   */
  
  function onError(error) {
      if (error.syscall !== 'listen') {
          throw error;
      }
  
      var bind = typeof port === 'string'
          ? 'Pipe ' + port
          : 'Port ' + port;
  
      // handle specific listen errors with friendly messages
      switch (error.code) {
          case 'EACCES':
              console.error(bind + ' requires elevated privileges');
              process.exit(1);
              break;
          case 'EADDRINUSE':
              console.error(bind + ' is already in use');
              process.exit(1);
              break;
          default:
              throw error;
      }
  }
  
  /**
   * Event listener for HTTP server "listening" event.
   */
  
  function onListening() {
      var addr = server.address();
      var bind = typeof addr === 'string'
          ? 'pipe ' + addr
          : 'port ' + addr.port;
      console.log('Listening on ' + bind);
  }
  </code></pre>
  
  <p>app.js</p>
  
  <pre><code>var express = require('express');
  var path = require('path');
  var AWS = require("aws-sdk");
  var app = express();
  var bodyParser = require('body-parser');
  
  var fs = require('fs');
  
  var cors = require("cors");
  
  app.use(bodyParser.json({limit: '50mb'}));
  app.use(bodyParser.urlencoded({limit: 150000000, extended: true, parameterLimit:50000}));
  
  var corsOrigin  ;
  
  if (process.env.NODE_ENV == 'production') {
     console.log('Adding CORS to the headers...');
     corsOrigin = 'prodserver';
  }
  else {
    corsOrigin = 'http://localhost:4200';
  }
  
  
  app.use(function(req, res, next) {
      res.setHeader('Access-Control-Allow-Origin', corsOrigin);
      res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
      res.set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
      res.set('Access-Control-Allow-Credentials', 'true');
      next();
  });
  
  
  
  var globSync          = require('glob').sync;
  var routes            = globSync('./routes/*.js', { cwd: __dirname}).map(require);
  
  
  AWS.config.update({
    region: "xxxx",
    accessKeyId: "xxxx",
    secretAccessKey: "xxxxxxx"
  });
  
  var ddb = new AWS.DynamoDB.DocumentClient();
  
  routes.forEach( function(route) { 
      route(app, ddb);
  });
  
  app.use('/', express.static(path.join(__dirname, 'dist')));
  
  app.use('/api/resources', express.static(path.join(__dirname, 'resources')));
  
  
  module.exports = app;
  </code></pre>