Recognize this ???
Yes !!! the CORS error. It rears its angry head from time to time.
What is it?
The first thing to understand is that this is not an error in the traditional sense but is instead a security measure to secure users from potential bad things that can happen on the interweb. This security measure is called the same-origin policy.
My attempt to define it:
A same-origin policy restricts a web-page from requesting data on another web-page with a different origin.
Imagine a situation where a browser didn’t implement a same-origin policy.
Any webpage could request data from any origin, meaning that any malicious site could use stored cookie or session data to access any social media accounts you have open, banks, or worse.
Without same-origin policy the world could look like this:
1.User logs into email account, Session cookie is created and stored on browser.
2. User logs into sketchysite.com. sketchysite.com uses the cookies to send request to email account. The returned data is captured and sold.
3. The next time you use your credit card you find its maxed out
Examples of same-origin
Examples of different origin
How to bypass it
Naturally, situations will arise where we need to safely bypass this policy and CORS is a way to do that.
Mozilla defines CORS as
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading of resources.
Option 1 🙅♂️
Well, we can actually make a change on the client-side where CORS can be bypassed by passing mode: ‘no-cors’ along with the HTTP request. Though this is not a recommended solution.
Note that “no-cors” only allows a limited set of methods and prevents the headers from being anything other than simple headers
fetch(url, {
method: ‘POST’,
mode: ‘cors’, // no-cors, *cors, same-origin,
headers: {‘Content-Type’: ‘application/json’}
})
Option 2 🙅♂️
Another solution I wouldn't recommend is to add a plug-in on your browser to bypass the cross-origin policy. These often behave like a proxy but can leave you open to attacks.
Popular plug-ins include:
Allow CORS: Access-Control-Allow-Origin
CORS Unblock
Option 3 💁♂️
The solution should be on the server-side. For Node and Express we can download the cors package https://www.npmjs.com/package/cors
$ npm install cors
This package will allow us to add a response header access-control-allow-origins
and specify which origins are permitted.
// Default = CORS-enabled for all origins
app.use(cors())// restrict to certain origin
app.use(cors({origin: “http://localhost:3001"}))
And Viola full control over the accepted origins without compromising security
I hope you have found this useful and thank you for reading.
Leave a comment