Lesson 20 / 23

Enabling CORS

Let browsers on other origins call your API.

What CORS is

Browsers block a page on origin-a.com from calling origin-b.com's API by default (the same-origin policy). CORS is the set of response headers that opts specific origins back in.

The cors package

npm install cors, then apply it as middleware — globally or scoped to specific origins.

import cors from 'cors';

app.use(cors({
  origin: ['https://myapp.com', 'http://localhost:4200'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
}));

Quick check: CORS restrictions are enforced by...

  • The server, before sending a response
  • The browser, based on response headers
  • The database
Answer

The browser, based on response headers — The server always processes the request; it's the browser that blocks the JS caller from reading the response if headers don't allow it.