0
0
Expressframework~5 mins

Why CORS matters for APIs in Express

Choose your learning style9 modes available
Introduction

CORS helps control who can use your API from other websites. It keeps your API safe by blocking unwanted access.

When your API is accessed by web pages from different websites.
When you want to allow only certain websites to use your API.
When browsers block your API requests due to security rules.
When building public APIs that many websites can use safely.
When debugging why your web app can't get data from your API.
Syntax
Express
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors({ origin: 'https://example.com' }));
Use the 'cors' middleware in Express to set CORS rules easily.
The 'origin' option controls which websites can access your API.
Examples
Allows all websites to access your API (open to everyone).
Express
app.use(cors());
Only allows requests from 'https://mywebsite.com'.
Express
app.use(cors({ origin: 'https://mywebsite.com' }));
Allows multiple specific websites to access your API.
Express
app.use(cors({ origin: ['https://site1.com', 'https://site2.com'] }));
Sample Program

This Express API uses CORS to allow only requests from 'https://myfrontend.com'. Other websites will be blocked by the browser.

Express
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');
});
OutputSuccess
Important Notes

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.

Summary

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.