express cors specific origins
To enable CORS (Cross-Origin Resource Sharing) for specific origins in an Express application, you can follow these steps:
- Install the
cors
package:
javascript
npm install cors
- Import the
cors
module in your Express application:
javascript
const cors = require('cors');
- Define the origins for which you want to allow cross-origin requests:
javascript
const allowedOrigins = ['https://example.com', 'http://localhost:3000'];
- Set up the CORS middleware with the specified allowed origins:
javascript
app.use(cors({
origin: function (origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
}));
In this example, the origin
parameter represents the requesting origin, and the callback
function is used to determine whether the request should be allowed or denied. If the origin
is included in the allowedOrigins
array, the callback is invoked with true
to allow the request. Otherwise, an error is passed to the callback to deny the request.
- Optionally, you can specify other CORS options as needed. For example, you can set additional headers, configure preflight requests, or allow credentials:
javascript
app.use(cors({
origin: function (origin, callback) {
// ...
},
methods: 'GET,POST',
allowedHeaders: 'Content-Type,Authorization',
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true
}));
These options allow you to customize the behavior of the CORS middleware according to your requirements.
By following these steps, you can enable CORS for specific origins in your Express application, allowing cross-origin requests from the specified origins while denying requests from other origins.