CORS
- Node.js course
- Advanced
- Lesson 20/83
- 5 min
Learn CORS with the cors middleware.
What is CORS?
CORS (Cross-Origin Resource Sharing) is the mechanism that lets a browser allow or deny requests from another origin. By default the browser blocks cross-origin requests (same-origin policy).
In Express you set CORS headers with the cors middleware. app.use(cors()) allows all origins. In production it is safer to allow specific origins: cors({ origin: "https://mysite.com" }).
The cors() middleware
Wiring the cors module into Express is simple. Import it with const cors = require("cors"), then apply it with app.use(cors()). Every response gets the Access-Control-Allow-Origin: * header.
There are customization options. You can list allowed origins with cors({ origin: [...] }) and restrict methods with cors({ methods: ["GET", "POST"] }). OPTIONS requests (preflight) are answered automatically.
Practice Log the type of cors
Import the cors module. Log typeof cors.
Starter code
// import the module
// log its typeSample solution
const cors = require("cors");
console.log(typeof cors);Expected output
function
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the module name
const cors = require("____")
const cors = require("cors")
Explanation: The cors module loads as 'cors'.
2 What does CORS provide?
- Encryption
- A database connection
- File compression
- Allows cross-origin requests Correct answer
Explanation: CORS allows cross-origin requests.
3 Match each piece to its role
| Term | Meaning |
|---|---|
cors |
Cross-origin |
Access-Control-Allow-Origin |
Allowed origin |
app.use(cors()) |
Enables CORS |
preflight |
Pre-request |