What is CORS? Fix Blocked by CORS Policy

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone welcome to wic code where in this video we're going to learn everything about cross origin resource sharing or cores and fix the blocked by course policy error specifically we will learn about the http headers involved with cores and how to create a course proxy and i also want to mention that all the code that i write in this video as well as a blog format will be available on my website in the link in the description so before we begin what is course well cores or cross-origin resource sharing is a mechanism enforced by the browser that uses origins to determine if a website at one origin can request data from a website at a different origin so before we go any further let's define what an origin is an origin is a combination of the protocol domain and port of the url used to access it two entities have the same origin only when the protocol domain and port number match websites with the same origin are allowed to get data from themselves as they have the same origin this is a policy also enforced by the browser that is known as the same origin policy if an origin is requesting data from a different origin then this is known as a cross-origin request and the course policy manages cross-origin requests to mitigate their risks for example wicco.com can't just blindly make requests to whichcodetools.com without passing some security measures or even worse imagine if random sites on the internet could make requests to our bank account if one origin is making a request to a different origin such as with an xml http request or using the fetch api it could possibly be restricted or denied by cores but so how does cores determine if a cross-origin request is loud well the answer is http headers cores is an http header based mechanism meaning it is implemented through the use of http headers two important headers for cores are origin and access control allow origin so the origin header is a request header that indicates the origin that caused the request for example if wicco.com is requesting data from a server the origin which would be https.com on port 8080 will be included in the request and now the access control allow origin header is a response header indicating whether the response can be shared with the origin requesting the data in other words this header determines if a request will be blocked by cores or not so let's give it let's give an example of these two headers working in tandem so let's say waitcode.com makes a request to whitcodetools.com well the request will contain the origin header set as origin and then listing witco.com and if the request is allowed the server will respond with the access control allow origin header as wicco.com specifying that this cross-origin request is allowed remember it's a quas cross-origin request because the origins of witco.com and whitcodetools.com are different if the origin specified on the request does not match the origin specified on the access control allow origin header on the response then the request is blocked by the course policy so as we usually do in this channel let's have a programming example to better understand this course error what we're going to do is actually create a course error ourselves and the way i'm going to do this is i we're going to create this but let me demo it to you real quick what we have is a client at origin a and a server origin b and we're going to run our origin b server it's listening on port 1 2 3 4 while origin a is on port 5050 so it's a different origin so it's a cross origin request but let's run this with live server which makes it act on port 5050 and now let's see what happens if we run this let's open up a console and we'll look for this error so when we send a request we can see it has been blocked by the course policy there's no access control allow origin header which basically means the server isn't allowing this origin here to make requests to it so we're going to build this and then we're also going to fix it but so to get started let's clear this console here and let's also close this down because we're going to be working in a new folder here and it gets started let's create a file called origin a.html and then let's just place some boilerplate code inside by using a shortcut which is an exclamation mark and now let's create a button to send a cross-origin request we'll give it an onclick attribute that will execute a function that sends a cross-origin request so now let's create this send request function and we will create this function inside script tags and now let's set up the request that will be sent to localhost1234 so to do this what we first do is create an xmlhttp object then we specify that it will be a get request that should be sent to localhost1234 with the protocol as http by using this method open and finally we send the request by using the send method and now when we click our button the request will be sent however we haven't set up our server to handle this request yet so to begin let's create a file called origin. or originp.js and import the node http library and the port that the server will listen on and remember this port will have to be different than the one our client is on as we want this to be a cross-origin request but so the node http library is a cord node module that supports many features of the http protocol and let's now use it to create an http server so the create server method creates an http server and this method takes a function known as a request listener so this function right here and this function handles requests from the client as well as the response sent back to the client if we receive a request let's send back the message hi so this write method sends a chunk of data to the client and the end method signals to the server that all of the response headers and body have been sent and as such the server should consider the response complete and now let's just have our server listen for incoming requests on the provided port this listen method here makes the http server start listening for connections on the specified port so now all we need to do is run our server and client so let's run our server and then let's run our client and hopefully we get the same result there we go so you can see we're getting this corsair and so we've created this corsair now but how do we actually fix it well a core's error being fixed relies on the server because the server is responsible for reporting the allowed origins if we control the server we simply need to respond with the proper header if we don't control the server it's a little trickier but we can but it can be done using a proxy so in this first instance we control the server because we have it right here and we can change the code so to fix a corsair on a server we control we simply need to add the specified origin to the access control allow origin header for example we just need to send back a header on the response allowing localhost 5050 and after we do this our program should work fine so to allow cross-origin requests on our server let's add the correct header actually instead of localhost i'm going to use 127.0.0.1 which is essentially the same thing except i had some weird issues sometimes using just localhost so i'd recommend using this instead but anyway the set header method here sets a single header value on the response that is returned to the client and this tells our server to allow requests from the origin http 127.0.0.1 on port 5050 and this tells our server to allow requests from the origin http 127.0.0.1 and port 5050 the url of our client sending the request and now let's add some code to our client to handle this response first let's create a h1 tag to display the message to the server and now inside our script tag let's get this element by its id and now let's handle the response from the server using our xml http request object so this code sets a listener on our xmlhttprequest object that is called whenever the ready state property of the request changes and the ready state property is a number zero through four that represents the status of the xml http request and when the ready state is four so when we check for its four here this means that the request finished and the response is ready to be read and the response is present in the response text property of the xhr so all we need to do is set the inner text of our h1 element to this response text which of course will be that message high so let's save this let's rerun our server and let's try sending a request again and so we can actually see that we still have this error here and the reason for this is because i already have a live server running here which must be using port 5050 while this one has been assigned to port five five fifty five hundred so this is fifty five hundred let's change our server here to allow origin 5500 and now if i send the request oh and we still have to change or restart the server so let's restart this and let's run it again and now we get high so we're not getting any more cores errors what instead we're getting back is the response but now let's talk about fixing a core's error when we don't control the server so fixing a corsair on a server we don't control is not as simple as setting the response header on the response instead we have to create a course proxy and a course proxy is a proxy that allows us to bypass core's security restrictions with a small change to the request url so in our previous programming example our client was sending a request to the target server directly however with a course proxy the browser sends the request to a course proxy which then forwards the request to the real server and the course proxy then returns the response with the access control allow origin header set so the course proxy acts as a proxy because it is an intermediary between the client requesting the resource and the server providing the resource and a course proxy works because cores is enforced by the browser and a course proxy is a proxy and not a browser and as such there is no course policy blocking it from sending the request to a different origin so let's create a simple course proxy now and so what we're going to be doing is making this course proxy work with our origin b server so first let's go back in here and let's remove this set header method so that we get blocked by cores again and then let's create a file called course proxy.js and import the http module and then let's create an http server the way we did previously note though that we named the request and response proxy request proxy response as this application is our proxy and now let's use the http module to send a get request to the origin b server which is listening on port 1234 right here so the htt module get method sends an http request or http get request to the provided url so this url here and it also accepts a callback function that accepts the response from the get request and now let's use some events present on this response object to work with the data so this response object present in the get method callback extends the event emitter class and as such we can use this on method and the on method adds a listener to the provided object listening for the provided event and when the event is fired the callback function or listener is called with the provided data and the events we are listening for here are data end and error this data event is emitted when a chunk of data is available the end event is emitted when there is no more data to be consumed and the error event is emitted when an error occurs and now let's respond to each of these events but so essentially when a chunk of data is retrieved we want to append it to a variable called raw data that is keeping track of the overall data and because the data here will be sent in chunks and next when the end event is emitted right here we want to set the access control allow origin header on our proxy response so the client doesn't get blocked by cores and we then write the data back to the client and call the end method to signal to the server that all of the response headers and body have been sent and finally if an error occurs we just want to log it to the console and now we just need to change the url in our client to request um to send a request to our course proxy instead of this origin here so instead of sending to one two three four we want to send it to one two three five so then we'll do server dot listen and then let's go into our client and change this to logo host one two three five and now let's duplicate this here so we have two of these and we need to rerun origin b and then let's also run our course proxy and now if we go here refresh this let's send a request and we get high so once again we're not blocked by cores but if we sent it directly to b instead refresh this sent it then we get blocked but instead we're going to work around this by sending a request to our proxy here which then sends a request to our the actual origin b server and then sets the header so we can actually access it access it and then it writes the data to us so it's a pretty nifty little trick so then if we go back in here send the request we get the data now real quick i just want to talk about coors proxy and security so it is great that we can use a course proxy to get around being blocked by cores however coors proxy should be used carefully and it is recommended to not use other people's course proxies as they can read and do anything with the full request and response like right here when we get this request we're sending it to this here but someone could tell you hey my course proxy sends it to the thing you think it does when really it could send it to some website that contains maybe your banking info and there could be some cookie set and they could get your bank information or something like that so they can do malicious things whatever they want with the request and the response so personally i would only use proxies that are trusted and in other words kind of ones just made by you but so it would be rare for a programmer to never come across a course um policy issue in their career but if you do now hopefully you know what to do so if this video was helpful um leave a comment let me know like subscribe um but besides that i look forward to seeing you in the next video and have a good one
Info
Channel: WittCode
Views: 9,988
Rating: undefined out of 5
Keywords: WittCode, wittcode, cors proxy, cors, reverse cors proxy, access allow control origin, origin, what is an origin, what is cors, blocked by cors policy, cors policy
Id: A7jpsbI3CE0
Channel Id: undefined
Length: 16min 34sec (994 seconds)
Published: Thu Apr 14 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.