If you want to allow clients from other origins to access your server, you need to enable CORS.
To enable CORS, we need to use a middleware.
What is a middleware?
In the Express framework, a middleware is a function that does something to the request before passing it over to route handlers.
This means you can put your middleware in two places:
- Before all your routes
- In a specific route the route handler
Before all your routes
You can place a middleware before your routes if you want the middleware to activate before hitting any routes.
// Middleware here// Routes comes after middlewareIn a specific route
You can place a middleware in a specific route if you want the middleware to target only that specific route.
app.get('path', middleware, routeHandler)Writing a middleware
Middlewares are written the same way regardless of where they’re placed.
All middlewares must:
- Take in three arguments —
req,res, andnext. - Call
nextafter they have done what they needed.
function middleware (req, res, next) { // Do something here // Call `next` when the middleware is done next()}The next function calls the next middleware. If there are no more middlewares, next will call the route handler.
That’s all you need to know about middlewares for now.
Next, you’ll learn to use middlewares to enable CORS.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson