DEV Community

Alestor Aldous
Alestor Aldous

Posted on

CORS Error in 5 minutes

PAIN

So What is CORS ?

CORS stands for Cross Origin Resource Sharing is mechanism that allows a website on one url to request data from another url . This error has been a pain for both front end and backend developer from start . Your webpage might be trying to fetch data from another url and end up with a error in the console

Trust me sometimes CORS Error is a huge pain for web dev out there :
apin

Something like this :

error

Well this happen because of the browser's security policy

Well what is this policy in simple words :

This policy allows a webpage from its own url but blocks anything from another url unless certain conditions are met.
Well if you open up the devtools you might be able to view the headers of request in which there is a origin header which specifies origin url if that request goes to the server in the same origin then its allowed by the browser

What happens when request goes to a different url :

This type of request is known as Cross Origin Requests
After reciving the request by the server it adds a
Access-Control-Allow-Origin header in the response .

If Access-Control-Allow-Origin does not match with Origin Header then browser prevents the response from being used by the client side app

So What's the solution ?

Well we can solve this issue at the backend side . We only need to set backend to respond with the proper header

If your express.js this issue can be solved using cors module

Install module by npm :

npm i cors
Enter fullscreen mode Exit fullscreen mode

Usage :

var cors = require('cors') 
Enter fullscreen mode Exit fullscreen mode

We can set express js to respond with a proper header with a 1 line middleware code

app.use(cors({origin:'http://yourawesomeurl.net'}))
Enter fullscreen mode Exit fullscreen mode

When facing a CORS Error

Step 1 :
Open up network tab of devtools find the response and check for

Access-Control-Allow-Origin

header . If it doesnt exist then you have to enable cors on server side
other wise the url might be a mismatch

Well if you dont own the server then you're doomed
doomed

And thats CORS Error in 5 minutes hope this articles helps you out

Conclusion :

Don't Worry Just Stay Awesome :D & Merry Christmas!!

Keep Coding !!!

🙏 Share with your friends on Twitter

Top comments (1)

Collapse
 
alestor_123 profile image
Alestor Aldous • Edited

I hope the article was helpful if so feel like and share