How to enable CORS — Intermediate — per router
Scope CORS to specific routers when only some paths need cross-origin access.
Learn: Router-scoped CORS limits cross-origin access to specific path prefixes—useful when only public API routes need browser access while admin routes stay same-origin only.
Supplementary examples
CORS on a single router
const cors = require("cors");
const publicRouter = require("./public/public.router");
app.use("/api/public", cors(), publicRouter);Course example
const router = require("express").Router();
const controller = require("./cors-enabled.controller");
const methodNotAllowed = require("../errors/methodNotAllowed");
const cors = require("cors");
router.use(cors())
router
.route("/:corsId")
.get(controller.read)
.put(controller.update)
.delete(controller.delete)
.all(methodNotAllowed);
router
.route("/")
.get(cors(), controller.list)
.post(controller.create)
.all(methodNotAllowed);
module.exports = router;
Additional references & examples
- cors package (npm)
Configuration options for CORS middleware.
- Express Router API
Router methods, route parameters, and mounting paths.