Cross-Origin Resource Sharing (CORS)
How to do that?
Well,
- Define strict CORS policies allowing only trusted origins.
- Use the wildcard (*) cautiously, it can expose your API to unintended access.
- 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