-
Notifications
You must be signed in to change notification settings - Fork 16
nodejs cors
Vijay Pratap edited this page Jul 20, 2024
·
2 revisions
This repository demonstrates how to configure CORS (Cross-Origin Resource Sharing) in an Express application.
- NodeJS installed on your machine
-
expressandcorslibraries installed
You can install the required libraries using npm:
npm install express corsEnsure you have the following environment variables set up in your .env file:
CORS_ORIGINS=http://example.com,http://another-example.com
CORS_METHODS=GET,POST,PUT,DELETE
CORS_CREDENTIALS=true
CORS_OPTION_STATUS=204The allowedOrigin function checks if the origin of the request is in the list of allowed domains. If it is, it allows the request; otherwise, it blocks it.
const allowedOrigin = (origin, callback) => {
const allowedDomains = process.env.CORS_ORIGINS.split(',');
const isOriginAllowed = allowedDomains.some(domain => origin && origin.includes(domain));
if (!origin || isOriginAllowed) {
callback(null, true);
} else {
const error = new Error('Not allowed by CORS');
callback(error);
}
}Here is an example of how to use the CORS configuration in your Express application:
const express = require('express');
const cors = require('cors');
const { allowedOrigin } = require('./utilities');
const app = express();
const corsOriginOptions = {
origin: allowedOrigin,
methods: process.env.CORS_METHODS,
credentials: process.env.CORS_CREDENTIALS === 'true',
optionsSuccessStatus: parseInt(process.env.CORS_OPTION_STATUS, 10)
};
app.use(cors(corsOriginOptions));
app.get('/', (req, res) => {
res.send('Welcome to the Express CORS Example!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});- Ensure that
CORS_ORIGINSis a comma-separated list of allowed domains. - Use environment variables to manage configuration settings like allowed origins, methods, credentials, and success status codes.
- Handle errors appropriately in a production environment, rather than just logging them or returning raw errors.