CORS express.js tutorial | Cross-Origin Resource Sharing in Node

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
now what is going on guys today we are going to talk about course also known as cross origin resource sharing what it is why you need it when you need it and how you can actually implement them in your express application so let's talk about the wording here first okay cross-origin resource sharing let's talk about resource first so on the web or at least if we're talking about rest everything or pretty much everything is like a resource right you have these http verbs get put pause delete and with these words you can do specific things with resources right if you do like get requests you can load like a particular resource like retrieve one if you make a post request you can create one and so on so somehow like if you look at just the word resource it's about how you can actually deal with resources and how these resources are shared and the next thing you might ask is well there's this word cross origin so what's an origin in the first place and an origin is like defined or characterized by three things it's the protocol the host name and the port so two origins are considered equal if and only if all of these three things are the same okay so if you have https mydomain.com on port 8080 and http mydomain.com port 8080 would be considered different origins because here the protocol is different right also if like only one only one component has to be different so there can be multiple components different right so if you go on port 8081 then not only is the protocol different but also the port so that means if at least one of these components are different then it is considered to be then the origins are considered to be different and when we're talking about cores we are merely talking about the communication between a browser and a server and this entire course thing is not relevant for like server to server communication it's like purely like a browser to a server kind of thing or like a course compliant http client if you want to be really precise which basically all major browsers are and the server and actually this entire thing sounds fancy but it's actually quite simple so this entire thing mainly relies on http headers so when you make a request or when your javascript code is making like a request to some server then the browser checks like the url where you want to make the request to and if it sees that it's actually a different origin so for example you are at mybank.com and you make some requests to myapigateway.com then the browser knows ah hold on a second like this is a cross origin request then in that case it typically attaches like this origin header okay so if you make a cross origin request the origin header is attached now if it's not across request then browsers typically don't attach it so say if this was not an api gateway but also like the server that has rendered this html page then you would not have this origin header i just wanted to point out this origin header first because you're going to see it like a lot if you look at the developer console but the main idea here is actually that the server is doing whatever it's supposed to do and then in the response it returns one additional header and this is like crucial and this header is called access control allow origin and what the server basically means with that it says hey i'm expecting like traffic from like this particular origin and then you basically get the response back and the browser if it sees like this access control allow origin header it looks at this header and then if if the value in the header and the own origin are not the same it's going to be blocked so you can see that in this case so say you have like some website i o you make like a request here the server might even do whatever it's supposed to do right maybe this is like some endpoint where you don't have authentication like it doesn't matter the service like the only thing the server is doing in addition is it's going to attach like this header and as soon as the browser sees this header it's going to compare it to its own origin and since the origin is somewebsite.com actually the browser would block and this is the important thing to understand so in this entire scenario the browser is actually like blocking and is not basically providing the response to like the javascript code so that means with course or by using like this header you have like very fine grain control over what websites um can talk to your server like what front ends okay so and this assumes like a course compliant http client um communication to like the server because what you could also say is well if this is just like an http header i can just take postman and i can just uh well i can just put in like the correct header and then the server is going to respond with whatever i want and that is totally true so obviously it's kind of like oh you need both parts right you need the server that returns the header and you need course compliant http client which postman is not right so postman doesn't care about what course had it returns right it will not return you an error that's not the point of it so this is the important thing to understand with course you have fine-grained control over what websites are actually allowed to make requests to your server and the actual request is actually being blocked like on the browser level if it's required and course also allows you to kind of relax like certain security requirements that you have on the web right so for example what you could do i mean would be a bad idea but what you could do is you could return like star which means i don't care like anyone can talk to my server if you return star then even mywebsite.com or even this other website here would be able to make a request typically you want to have a very fine-grained control over who accesses your who has access to your resource yeah and that is pretty much like the entire idea of course yeah and there's one more thing i want to talk about and that is this idea of course pre-flights so in this entire web security model some requests are considered to be complex or a little bit dangerous and that's why there's like additional security actions so to say that the browser is performing to make sure that you're not doing like an invalid operation and again this only applies if we're talking about like cross-origin requests so that means if this is mywebsite.com and this is also mywebsite.com you will not have a preflight okay so this only applies if this is like my some other origin right so for example my api gateway.com and the idea here is that if you try to perform certain operations or if you have specific custom headers then instead of directly making the request or in that the javascript is trying to do the browser is going to preflight this request so that means it's going to make a http request with um like to this uh to the server with the options http verb yeah so this options verb this options request is basically a normal http verb so just like get put post delete but it does not have a request body okay so you make this request and the server hopefully like responds if it does not respond the browser is not going to make the follow-up request usually like with the 200 status and the server also or typically responds with additional headers so for example there's like one header where you can specify which http verbs you allow so for example you might respond like with just delete and then the browser will look at these headers and we'll say oh yeah okay like the service said in my preflight request that it allows this particular delete request so i'm going to do the follow-up request so for one you can specify which or the server can specify which http verbs it allows but it can also send this access control allow origin header back and if this header does not match like with the website's origin the browser is also going to block so as you can see the browser is basically being a little bit careful but before it tries to attempt like a dangerous operation and that is mainly the idea of having like a pre-flight so certain things are considered to be critical that's why to be sure we make options requests we ask the server hey man what do you like what operations can i do it will return hey you can do you can use the following http verbs we require you that the request is coming from the following origin and then the browser is going to kind of look at the headers and then if all the conditions match like the http verb is allowed and the the origin where the server expects traffic from so basically from this header is the same then it will actually perform the request otherwise it's going to block and by the way this behavior it cannot be turned off so preflights cannot be turned off and cores itself also cannot be turned off okay so there's no way that you can use some javascript or whatever to turn this off simply because it would be a big security issue yeah so now that we have seen preflights let's uh just take a look look at the code and let's just see how it works so i have a pretty let me make this a little bit bigger maybe i don't know i think it's fine right i have like a simple express application so it's just a server that runs on port 8080 and we have like a router and this router has like a you can make a get request and you can also make a delete request to slash item so that's it pretty much i just wanted to show you like how this works let me just run this okay so i have not one installed i'm just going to run this and i just want to show you how that works i'm just going to make a get request and let's just look at the headers that we get back so as you can see we have a couple of headers x powered by content type content length etag connection but nothing about like uh course or anything and this is what we want to change because you actually need like a course header in order for your front end to talk to your backend i'm just going to stop like the server and i'm going to install one additional package which is called course so this is like a very popular popular package over here you can see its documentation there um the usage is actually very very simple so the idea is you have like this package you import it and if you want to allow all cross-origin requests you just like call this thing and it's always going to it's going to return like the star in the request which means i don't care about like the origin or you can also specify that you only allow specific types of origin and that is actually the case you should do so having like this star like i would really not recommend doing that right because you know which uh front end is going to consume like the request so you should restrict you should restrict that and the way you can do that is let's just go back and now we got the package installed so i'm just going to make a directory and i'm going to say create a file here i'm going to call it index.js and inside of here i'm just going to import like this package and i'm just going to say course and then i'm going to paste this value here from the documentation what you can see here this that we are specifying like this origin field and this is essentially the value that we're going to return in this access control allow origin i think in our case it was actually mybank.com right if you have preflight requests then sometimes you have like uh the http status 204 which not all browsers support so that's why it's a very good practice to use like 200. and the key thing here to understand is that you need to use like this package and pass like your options and what this returns is it's actually returning a middleware so this call here returns a function like a function like this request response next that you know does some stuff and eventually oops that does some stuff and then eventually calls i don't know next okay this is important to understand it might be a little bit unintuitive if you're not um like if you haven't seen it before that like a function call itself is returning a function but that's basically how this works okay and the only thing we need to do to make this work is we just need to import it here and make sure that you import dot slash course so not the package course but dot slash course which is like our custom course middleware and then directly before and this is important before you plug in like your router just plug in like your course middleware i'm just going to call this course middleware right to indicate that it's like custom middleware okay so that's it um and it's pretty simple so let's just run this and let's go to postman yeah so let's just try this out let's make a request and let's take a look at the headers so you can see now we have like this access control allow origin header and it is exactly mybank.com so the same thing that we specified over here and now it's getting interesting so because what we could do here is we could allow multiple origins so let's say i want to make mybank.com and i want to have i don't know my bank mybank2.com right this is like a different host so that's why the origins are different and now the package behaves in an interesting way because if you now make this request you can see that wait hold on a second like somehow the header is gone and that makes actually might be a little bit confusing at first but actually it makes total sense so initially if you only have one value then the server knows exactly what value for the header it has to return but if you specify more than one value then it actually doesn't know right because if you allow requests from two origins how should the server know which origin or which value it should return right so let's assume you're on mybank2.com and it randomly returns mybank.com well then the browser would block which you don't want and that is actually where this origin header comes into play so if you go to this headers tab you can basically say okay i want to activate like um origin like i want to send the origin header along that's what we've talked about right if it's a cross origin request the browser is going to send the origin header along and in here you can say okay it's like mybank.com and this is also interesting let's just try this out and see what happens and this is interesting because you see it's not there hmm why could it not be there look at the origin ah little mistake it needs to be https right because remember the protocol is important so let's try this again you make https ah and now you have it yeah okay well that makes sense if you have more than one value and you don't have an origin header in the request then it's not going to return the actual adder makes total sense and what you can also do is let's say i have like my bank two you can see now it's like mybank2.com interesting and let's say mybank3 which we haven't specified then you can see again it does not have the header and by the way if it does not have this access control allow origin header the browser is going to block right away okay because it knows uh it's it's a cross-origin request but there's no header from the server so it's going to block so this is the important part to understand and the only other part i wanted to cover are like the options requests by default if you have like the express server up and running and you just make like some options requests you can see that okay it somehow returns status 200 but there's like no access control allow origin header what you can see here is that it does have this get head put patch and so on which is an additional header which is the default that the server has so it basically says hey if you're calling this you're allowed to use the following http method http verbs which you can also restrict in the course settings by the way but you can find that in your documentation so that is interesting now the issue is as i already said if you don't enable pre-flights if the browser is making this preflight and it's just and it just sees like this response and there's no access control allow origin header it's not even going to make the second request right so it's not even going to make this request over here because the server did not return like a proper course header and this is what we need to plug in right here and it's actually quite simple so let's go to a file and what you will see very often is that people do something like app.options and then they put star and then they put the course middleware and what this basically means is for all option requests run them through our course middleware if we go back yeah maybe let's maybe let's leave out the origin header for now okay let's just run this you can see okay still no headers makes total sense because remember we have this array of two origins if you go back to this and you delete that and you delete this and you save this and by the way i have like hot reload enabled and you run this oh yeah interesting okay then you see the access control allow origin header again so always remember if it's only one value you always get this thing if it's if you have two values then the behavior depends uh i think we should not have deleted it because i just wanted to show you what happens if um if you have two values so as you can see you don't get anything if you put like an origin that is not on the allowed list you can also see that you don't get a header but if you do put an origin that is on the allowed list then bam you see you get the access controller origin and then in that case the browser is going to make the request so i know it's a it's a lot of details for like this little package so to say but i think these are the issues that you encounter when you are actually trying to implement this because you know most people they will just show you like this and that's it and you might be wondering well why is it still not working okay and i just wanted to show you like all the details and the caveats that you need to know in order to properly use this package so as you can see it's very simple and if you want to know more about it i would highly encourage you to read the documentation here yeah you can even have like a custom function that runs here if you want there's also more things you can specify so not just the origin but you can specify the methods so right this is the header we have seen before you can specify like credentials this is very important when it comes to sessions and to logging things in i also have a video series about that if you're interested that's it pretty much thank you so much for watching leave a like and subscribe i hope this helped you to understand this entire concept like properly not just on the surface but like how this package behaves and i think once you get the hang of it it's like really easy just include it in your projects and you'll be fine and if you're implementing a server to server communication like don't implement this package obviously because you don't want like a browser to talk to your server right if you're just talking about server to server communication yeah so that's it pretty much uh thank you so much for watching leave a like and subscribe and i hope i'll see you in the next video if you have a question you can leave a comment down below or also send me tweet my twitter handle is at productioncoder thank you so much and see you around bye
Info
Channel: productioncoder
Views: 4,579
Rating: undefined out of 5
Keywords: cross origin resource sharing, cors error, cors policy, cors explained, cors express js, express cors tutorial, node cors error, node cors not working, express js cors, javascript cors, cors node js tutorial, cors node express, cors example javascript, cors example, cors preflight explained, cors preflight request, express cors preflight, js cors preflight, express cors middleware not working, node cors middleware, express cors setup, access control allow origin
Id: woXBXJgGQvQ
Channel Id: undefined
Length: 21min 39sec (1299 seconds)
Published: Mon Mar 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.