# Enabling CORS — Express.js Fundamentals: Routing, Middleware and APIs

Source: https://www.skillbyai.com/en/expressjs/ex-cors

> Enable CORS safely with the cors package using an allow-list of origins.

## 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.

```javascript
import cors from 'cors';

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

**Quiz:** CORS restrictions are enforced by...

- [x] The browser, based on response headers
- [ ] The server, before sending a response
- [ ] The database
- [ ] The reverse proxy only

*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.
