CORS middleware helps your server allow or block requests from other websites. It keeps your app safe and controls who can use your data.
0
0
cors middleware setup in Express
Introduction
You want your API to be used by web pages from different websites.
You need to allow only specific websites to access your server.
You want to prevent unauthorized websites from calling your API.
You are building a frontend and backend on different domains.
You want to fix errors related to cross-origin requests in the browser.
Syntax
Express
import cors from 'cors'; import express from 'express'; const app = express(); // Use default CORS settings app.use(cors()); // Or customize CORS options const corsOptions = { origin: 'https://example.com', methods: ['GET', 'POST'], allowedHeaders: ['Content-Type', 'Authorization'] }; app.use(cors(corsOptions));
Import the cors package and use it as middleware in your Express app.
You can use default settings or pass options to control who can access your server.
Examples
This allows all websites to access your server resources.
Express
app.use(cors());
This only allows requests from https://mywebsite.com.
Express
app.use(cors({ origin: 'https://mywebsite.com' }));This limits allowed HTTP methods to GET and POST.
Express
app.use(cors({ methods: ['GET', 'POST'] }));This allows multiple specific websites to access your server.
Express
app.use(cors({ origin: ['https://site1.com', 'https://site2.com'] }));Sample Program
This Express server uses CORS middleware to allow only requests from https://example.com. When you visit http://localhost:3000, it responds with a greeting message.
Express
import express from 'express'; import cors from 'cors'; const app = express(); // Allow only https://example.com to access app.use(cors({ origin: 'https://example.com' })); app.get('/', (req, res) => { res.send('Hello from CORS-enabled server!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Browsers enforce CORS, so this middleware mainly affects browser requests.
Always specify origins carefully to avoid security risks.
You can also configure other options like allowed headers and credentials.
Summary
CORS middleware controls which websites can access your Express server.
Use app.use(cors()) for open access or pass options to restrict access.
Proper CORS setup helps keep your app safe and avoids browser errors.