Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 25, 2022 04:42 pm GMT

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

Usage :

var cors = require('cors') 

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

app.use(cors({origin:'http://yourawesomeurl.net'}))

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


Original Link: https://dev.to/alestor_123/cors-error-in-5-minutes-2doa

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To