October 22, 2024
Chicago 12, Melborne City, USA
security

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header


Currently, my CORS setup only allows access from specified domains depending on the environment. However, I can still perform operations from Postman, curl, etc. What’s going wrong?

const allowedOrigins = [
  'https://xxxx.app',
  'https://www.xxxx.app',
  'https://dev.xxxx.app',
  'https://www.dev.xxxx.app'
].map(origin => origin.replace(/\/$/, ''));

const corsOptions = {
  origin: function (origin, callback) {
    const normalizedOrigin = origin ? origin.replace(/\/$/, '') : null;

    if (!normalizedOrigin) {
      return callback(null, true);
    }

    if (allowedOrigins.includes(normalizedOrigin)) {
      return callback(null, true);
    } else {
      const msg = 'CORS origin not allowed: ' + normalizedOrigin;
      return callback(new Error(msg), false);
    }
  },
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], 
  allowedHeaders: ['Content-Type', 'Authorization'], 
  credentials: true,
};

app.options('*', cors()); 

if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'development') {
  app.use(cors(corsOptions));
} else {
  app.use(cors());
}



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video