🎓 A1Learner
🔍
0 of 50 lessons completed

CORS

CORS is a browser rule about which websites may call an API. It stops a page on one origin from reading answers from another origin without permission.

The API grants permission

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  next();
});

One origin instead of a star

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5173');

Reading the header on the response

response.headers.get('access-control-allow-origin')

Example

import express from 'express';

const app = express();

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  next();
});

app.get('/notes', (req, res) => {
  res.json([{ title: 'Buy milk', done: false }]);
});

const server = app.listen(0);
await new Promise((resolve) => server.once('listening', resolve));
const port = server.address().port;

const response = await fetch('http://localhost:' + port + '/notes');
console.log('CORS header: ' + response.headers.get('access-control-allow-origin'));
const notes = await response.json();
console.log(JSON.stringify(notes));

await new Promise((resolve) => server.close(resolve));

Key points

  • CORS is short for Cross-Origin Resource Sharing.
  • An origin is a website address, made of its scheme, host, and port.
  • The browser blocks a page from reading an API answer from another origin.
  • The API grants permission with a CORS header on its response.
  • The header names the origin that may read the answer, or a star for any origin.

In this example, the server sets the CORS header on every response before the route runs. The script fetches the notes and prints the header it actually received. The star means any origin may read the answer. The second line shows the notes body, so the request itself worked.

Note

CORS guards the browser only, so a Node script is not blocked by it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the CORS header do?