Back to course

Cross-Origin Resource Sharing (CORS)

How to do that?

Well,

  1. Define strict CORS policies allowing only trusted origins.
  2. Use the wildcard (*) cautiously, it can expose your API to unintended access.
  3. Ensure CORS headers are set only for intended HTTP methods and headers.

Example:

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'your-safe-origin.com');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

Want to learn more? Check out the MDN Web Docs on CORS