Cross-origin resource sharing? what is it? Have you ever stumbled upon a CORS error?
OF COURSE… now let's get to the CORE of it…
🏁Some information before start
- The user will use a browser to access a website. I will refer to this as a
client
- The
client
will exchange resources (images, stylesheets, scripts, data, …) with aserver
through API calls.
ex:/getUser
is an endpoint that will be stored on thesever
and will return a list of users - The
client
and theserver
communicate over a network using theHTTP protocol
client
→server
is a request vs.server
→client
is a response- The
HTTP header
consists of key-value pairs and allows theclient
and theserver
pass additional information with a request or a response
👽 What was used before CORS?
JSONP
— stands for JSON with padding is a way old fashion technique used in JavaScript to make a request to another domain using the script tag:
<script src="myscript.com"/>
but…
- JSONP supports only
GET
requests - The response coming from the request will be automatically executed by the browser, that is, we can’t parse it
- No HTTP error code is returned to track the status of the request (success, redirection, client/server error…)
🖼️ The big picture of CORS
- Modern browsers support the
Same origin policy
. They automatically allow you to fetch anything from your domain, but they block any external/cross-origin requests unless certain conditions are met. - The conditions may be specified in the
HTTP header
🔄 How it works?
Let's say the client is hosted on “www.laramo.com” and the server is “www.getYourData.com”
- CORS will allow you to specify what domains can access your endpoint hosted on the server.
- CORS will also allow you to specify what methods are allowed to be called (GET, POST, PUT, DELETE, …)
- If the
client
requests towww.getYourData.com/summerTodos
, this endpoint should specify the value of the origin they allow to call this endpoint like so:Access-Control-Allow-Origin: “www.laramo.com”
- In
Node.js
you can use thecors
library to simplify the syntax a little:
const cors = require('cors');
app.use(cors({
origin: "www.laramo.com"
))
✈️ Preflight
- Preflight is a special cached request sent to the server before calling the actual endpoint to see if the server allows this type of method.
- This usually applies to methods like
DELETE
andPUT
that have an after-effect on the data. - On the server, we will specify the
method
that is allowed to be expected by the client - Hence if the client is sending a
PUT
request but the server is only expectingGET
requests, it will be rejected with the following error:
OPTIONS
https://getYourData.com/
net::ERR_ABORTED 405 (Method Not Allowed) Access to fetch athttps://getYourData.com/
from origin'http://laramo.com
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
const cors = require('cors');
app.use(cors({
origin: "www.laramo.com",
method: "GET"
// Can be also an array of possibilities ["GET", "POST", "PUT"]
))
💁 Request headers to send to the server:
When you send a request to the server, you may specify the following parameters in your request header:
Origin
→ where the request is initiatedAccess-Control-Request-Method
→ GET, POST…Access-Control-Request-Headers
→ additional information to add to the request such as the type of data:
"Content-Type", "text/xml"
📙 Response headers to receive from the server:
Access-Control-Allow-Origin
→ what origins are allowed to request this server, that is, where can the request be initiated fromAccess-Control-Allow-Methods
→ what methods are allowed to be sent to this serverAccess-Control-Allow-Credentials
Access-Control-Expose-Headers
Access-Control-Max-Age: how long do you want to cache your headers for, default is 5s
Access-Control-Allow-Headers
Lastly…
Fun fact: img
tags don’t require CORS at all and can access any public image
<img src="https://cdn.vox-cdn.com/thumbor/wfbQ3XccV6SxGMt1l6zBPL3Xg7o=/0x0:1192x795/1400x1050/filters:focal(596x398:597x399)/cdn.vox-cdn.com/uploads/chorus_asset/file/22312759/rickroll_4k.jpg"/>
That’s it for today’s COURSE :),
Go code now,
Lara Mo