When you use XHR or Fetch to request a resource from a browser, you may run into a CORS error. (This is very common).
At this point, you’ll probably have a few questions:
- What is CORS?
- What is an opaque response?
- What is the
no-corsmode? - What is the
Access-Control-Allow-Originheader?
We’ll answer these questions in this lesson.
Let’s begin with the most obvious one.
What is CORS?
CORS is short for Cross Origin Resource Sharing.
It enables two things:
- It lets you fetch resources from a browser.
- It lets the server decide whether to accept your request.
Servers decide whether they want to accept your request with an Access-Control-Allow-Origin header. (This is a header set by the server).
If the server does not set an Access-Control-Allow-Origin header, or if the header doesn’t contain your origin, you won’t be able to get resources from the server via a browser.
Your only choice, if you want to fetch resources from that server, is to use another server. That’s because servers are not constrained by CORS.
What’s an origin?
An origin contains three things:
- A Protocol (the
file://,http://orhttps://part) - A Host (the domain name)
- A Port (the number that comes after the domain name)
# Example of originshttps://zellwk.comhttps://students.magicaldevschool.comhttps://api.github.comhttp://locahost:3000In case you’re wondering, the root of an API is also the origin of the API.
You’ll learn how to allow specific origins to access your server later.
Opaque responses are usually useless
Opaque responses are responses that don’t return CORS headers. If you send an opaque response, you won’t be able to read the data returned or even view the status of the request — so you won’t know if the request is successful.
Opaque responses are useless because we need to know the status of the response — otherwise, we won’t know what to do next.
So instead of using no-cors, a better alternative is to send requests through servers.
Wrapping Up
The best way to mitigate CORS errors is to send requests from servers — this is almost everything you need to know about CORS for now.
This is also why servers are important.
But before we dive into servers, you still have a few more things to learn about Rest APIs.
Next, you’ll learn about the anatomy of a response.
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