You can configure CORS by setting 3 headers:
Access-Control-Allow-OriginAccess-Control-Allow-MethodsAccess-Control-Allow-Headers
All 3 headers are mandatory.
Setting headers
You can set headers with the res.set method.
function middleware(req, res, next) { res.set(headerName, value)}About Access-Control-Allow-Origin
If a request comes from a browser, the Access-Control-Allow-Origin header lets you decide whether to accept the request.
All requests from servers will be accepted because servers are not restricted by CORS.
Access-Control-Allow-Origin takes in two possible values:
- A specific origin like
http://localhost:8080 - A wildcard (
*) that accepts all origins
Here’s how you would allow requests from a specific origin:
app.use((req, res, next) => { res.set('Access-Control-Allow-Origin', 'http://localhost:8080') next()})Once you have this, you should be able to access your server from the client without encountering a CORS error.
// Frontend JSzlFetch('http://localhost:3000').then(response => console.log(response.body))
When to accept all origins
You should only accept all origins if you’re building a public API that can be accessed by any client. If you’re not doing this, you should not allow all origins.
That said, here’s how you would accept all origins:
// Allow all origins.// Do not use unless you're building a public API that can be accessed by any browserres.set('Access-Control-Allow-Origin', '*')Accepting multiple origins
Access-Control-Allow-Origin only takes in one origin value.
If you want to allow multiple origins, you need to create an array of whitelisted origins.
If the request comes from a whitelisted origin, you set Access-Control-Allow-Origin to that origin.
Here’s the code you need to do this:
app.use(function (req, res, next) { const whitelistedOrigins = ['http://localhost:3001', 'http://localhost:8080'] const origin = req.headers.origin const found = whitelistedOrigins.find(o => o === origin)
if (found) res.set('Access-Control-Allow-Origin', origin) next()})About the other two headers
To understand the other two headers, you need to take a deeper dive into CORS and understand the difference between a normal request and a preflight request.
Understanding Preflight requests
A preflight request is a tiny request that is sent before the main request. It is used to check whether the server would accept the main request.
- Preflight requests are only sent if the request is a complex request.
- If the request is simple, the main request will be sent immediately instead.
Imagine calling a restaurant to check if you can book a table. That call is a preflight request.
Here’s the difference between simple and complex requests:
- Simple requests:
- They must be a
GET,HEAD, orPOSTrequest - They must not contain any headers except for
Accept,Accept-Language,Content-Language,Content-Type, andRange - The
Content-Typeheader must be one ofapplication/x-www-form-urlencoded,multipart/form-data, ortext/plainonly.
- They must be a
- Complex requests:
- They are requests that do not conform with all of the required rules for simple requests
Most API requests nowadays are complex requests because:
- They usually use the
application/jsoncontent type. - They usually require the
Authorizationheader for authentication.
Access Control Allow Methods
Access-Control-Allow-Methods determines what methods can be used for the main request.
The default is GET, HEAD, and POST (which are allowed methods for a simple request).
For most APIs, you need to allow all the methods you’ve learned so far plus the options method (which is generally only used for preflight requests).
res.set( 'Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS',)If the request method is OPTIONS, you also need to respond with a 200 status code to tell the client you’re accepting their request. Without this, a preflight request would fail.
if (req.method === 'OPTIONS') return res.status(200).end()Access Control Allow Headers
Access-Control-Allow-Headers determines what headers are allowed in the main request.
You need to list out all the headers you want to accept here.
Minimally, your server should accept 2 headers:
Content-TypeAuthorization
res.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')That’s all you need to know about enabling CORS for your server!
Many people use the cors package to configure CORS.
You can do that too.
I just felt it was easier to set these headers manually after I learned about them.
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