# Enabling CORS — Express.js

Source: https://www.geekswithgeeks.com/en/expressjs/ex-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.

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

- [ ] The server, before sending a response
- [x] 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.
