-
Notifications
You must be signed in to change notification settings - Fork 13
nodejs cors
Vijay Pratap edited this page Jul 20, 2024
·
2 revisions
- About CORS
- What is CORS
- Use Cases of CORS
- Implementation of CORS
- Setup Fresh NodeJS Project
- Install Packages expressjs, cors
- Create Sample Route
- Use CORS
- Complete Code Example
CORS (Cross-Origin Resource Sharing) is a security feature in browsers. It controls how resources like data and content are requested from different domains. This means it allows or restricts resources on a web page to be accessed from another domain.
- Web API Integration: Allows your web app to connect with APIs hosted on other domains.
- Content Sharing: Lets websites share resources such as images, stylesheets, and scripts from other domains.
- Security Control: Protects resources by specifying which domains are allowed to make requests, preventing unauthorized access.
mkdir express-cors-demo
cd express-cors-demo
npm init -y
npm install express cors
Create a file named server.js
and add the following code:
const express = require('express');
const app = express();
app.use(express.json());
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Welcome to Express CORS Demo');
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Add CORS middleware to the sample route:
const cors = require('cors');
const allowedOrigin = (origin, callback) => {
const allowedDomains = ['http://example.com', 'http://another-example.com'];
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);
}
};
const corsOptions = {
origin: allowedOrigin,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true,
optionsSuccessStatus: 204
};
app.use(cors(corsOptions));
Here is the complete code combining all steps:
const express = require('express');
const cors = require('cors');
const allowedOrigin = (origin, callback) => {
const allowedDomains = ['http://example.com', 'http://another-example.com'];
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);
}
};
const app = express();
app.use(express.json());
const corsOptions = {
origin: allowedOrigin,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true,
optionsSuccessStatus: 204
};
app.use(cors(corsOptions));
app.get('/', (req, res) => {
res.send('Welcome to Express CORS Demo');
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});