Introduction
CORS helps control who can use your API from other websites. It keeps your API safe by blocking unwanted access.
Jump into concepts and practice - no test required
CORS helps control who can use your API from other websites. It keeps your API safe by blocking unwanted access.
const cors = require('cors'); const express = require('express'); const app = express(); app.use(cors({ origin: 'https://example.com' }));
app.use(cors());
app.use(cors({ origin: 'https://mywebsite.com' }));app.use(cors({ origin: ['https://site1.com', 'https://site2.com'] }));This Express API uses CORS to allow only requests from 'https://myfrontend.com'. Other websites will be blocked by the browser.
import express from 'express'; import cors from 'cors'; const app = express(); // Allow only https://myfrontend.com to access this API app.use(cors({ origin: 'https://myfrontend.com' })); app.get('/data', (req, res) => { res.json({ message: 'Hello from API!' }); }); app.listen(3000, () => { console.log('API running on http://localhost:3000'); });
CORS is enforced by browsers, not by the server itself.
Without proper CORS, your API might be blocked when called from web pages on other domains.
Always set CORS rules carefully to balance security and usability.
CORS controls which websites can use your API.
It protects your API from unwanted access by other sites.
Express makes it easy to set CORS rules with middleware.
const express = require('express');
const app = express();
app.get('/data', (req, res) => {
res.json({ message: 'Hello' });
});
app.listen(3000);
What is missing to allow cross-origin requests safely?