Cross-Origin Resource Sharing (CORS) is a security measure browser use to control requests between different web origins. When your web page wants to fetch data from a different domain, CORS ensures it’s done securely.
CORS Headers:
Access-Control-Allow-Origin: Specifies which origins can access the resource.Access-Control-Allow-Methods: Defines which HTTP methods are allowed for accessing the resource.Access-Control-Allow-Headers: Lists allowed HTTP headers during the actual request.Access-Control-Allow-Credentials: Indicates whether credentials (like cookies) can be included in the request.
Using the CORS NPM Package:
Install CORS:
npm install cors
Implement in Express:
const express = require('express');
const cors = require('cors');
const app = express();
// Enable CORS for all routes
app.use(cors());
// Your routes and application logic go here
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
The cors NPM package simplifies CORS implementation in Express, ensuring secure communication between your web app and different origins.