Configuring CORS
Allowing Specific Origins
If you want to restrict CORS to a specific origin, you can set it as follows:
const corsOptions = {
// Allow only requests from this domain
origin: 'http://example.com',
};
app.use(cors(corsOptions));
Allowing Multiple Origins
You can also allow multiple origins by specifying them in an array:
const allowedOrigins = ['http://example.com', 'http://another-domain.com'];
const corsOptions = {
origin: function (origin, callback) {
if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
};
app.use(cors(corsOptions));
Allowing Specific Methods
To allow only specific HTTP methods, use the following configuration:
const corsOptions = {
// Only allow GET and POST requests
methods: ['GET', 'POST'],
};
app.use(cors(corsOptions));
Supporting Credentials
If you need to support credentials, you can enable them with this configuration:
const corsOptions = {
origin: 'http://example.com',
// Allow credentials like cookies
credentials: true,
};
app.use(cors(corsOptions));
Customizing Headers
To specify which headers are allowed in CORS requests, use this approach:
const corsOptions = {
// Allow specific headers
allowedHeaders: ['Content-Type', 'Authorization'],
};
app.use(cors(corsOptions));
NPM CORS
Cross-Origin Resource Sharing (CORS) is a fundamental security mechanism implemented by web browsers to prevent unauthorized access to resources on a web page from different origins. In Node.js, CORS management is essential when building APIs that need to be consumed by clients running on different domains.
Table of Content
- What is CORS?
- Need for CORS in Node.js
- Using npm Cors Package
- Basic Usage
- Features
- Configuring CORS
- Conclusion