How to Fix The Cors Error with a Reverse Proxy

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody today we're going to be looking at setting up a reverse proxy in express and if you're wondering what a reverse proxy is it's essentially a server that we set up in order to call an api endpoint and then return the result to the browser as if we called the api endpoint directly now you might be wondering why do we need to do that why don't we just call the api endpoint directly and i've got an example here that i've set up which is just a little view component and that calls an api i found on the internet this one is for public holidays in great britain in 2020 it just returns a json response and i'm just printing the raw json response in the browser so if we copy and paste this url into the browser this is the result we get nice and simple just a nice json response and that's exactly what we would expect to receive when we called it from our view app so let's have a look at our view app and oh we've got a network error and if i refresh that i'll just show you that is actually what is happening and the reason we've got that is because we've got a cause issue and so we've been blocked by this api from accessing the api directly from the browser which is what cause is about so in order to bypass this we want to set up our own server that calls the endpoint and returns it back and we can control cores on our own server if you're unfamiliar with cause and if you're a front-end developer you've probably come across it before it's something that the browser uses to prevent cross-site request forgery attacks um it's not really used on servers and it's quite complicated as to how it all works and we're not going to go into that today but just it's important to know that this is something that happens in the browser but wouldn't happen directly from our express server or in our case our reverse proxy so let's have a look at how we can build that okay let's start by creating a new project directory and we're just going to make a directory and we'll call it reverse proxy like so and then let's just change into that directory there we go and we're just going to run npm init to initialize our npm project um that's fine for the package name version 1.1 don't need a description um none of these these things really matter for our purposes we're not going to bother with a repository we don't need to worry about keywords i like to just type my name in is c license is fine and is that all okay yes it is and so we've now initialized our package json and we should now be able to open that up in our ide okay as you can see um i've got our reverse proxy project now open inside the ide and the first thing we're obviously going to want to do is bring in express so mpm install express and save prod and then just let that install okay now that we've installed express we just want to create a new javascript file which we're going to call app and then we just want to require express and then just set up our app and we're just going to create a little get root which just and if you've used express before you're probably quite familiar with what i'm doing here i'm just basically sending hello world to the browser and then we just need to our app to listen and we'll have it listed on port 3000 so we've basically got um a little service out there this actually works and all we need to do is come over to our terminal and we just need to write node app dot js that should run and then if we come over to our browser and let's open up another window and it'll be local host 3000 and as you can see we've got our little hello world open so our express server is up and running the next thing we're going to want to do is we're going to want to match the routes on our server to the roots of our api so here you can see we have public holidays 2020 gb and we're going to want to be able to say logos 3000 and we're going to want to call that same endpoint on our api and then it passes that information through to the api that we're calling at the minute though obviously we get um i cannot get public holidays 20 20 gb because we actually don't have a route for that so rather than mapping every route for the api instead we're going to use a little bit of a little regular expression so let's come over here and we can do the colon which means we're going to start using a parameter and that's end points and our regular expression is just going to match any kind of basic url route so obviously they've got forward slashes in them um word characters and you can have a dot and you can have a dash and you have them zero or any number of times and then what we're going to want to do is we just want to go and restart our server so let's come over here and i'll just close this down and re-fire it back up and if we come over here and hit refresh you can see we've now got hello world at our route so basically it means that our server um is now recognizing uh this root here oops it looks like i made a typo so i just type sorry that should be called end point uh yep so all that's happening there is that it matches any route and it would actually do it with anything so it doesn't really matter what it is foo for example and it still calls that so basically we've matched any kind of get request through to our proxy server and so now we just want to look at how we can get that and then make a call to the actual api endpoint um that we're using in this in this tutorial so that's this api endpoint so to make api calls i like to use axios so if we come over to the terminal and let's just open up a new window npm install axios save okay now that's installed we just need to come over to our app and import it so const axios equals require axios like say and then i just have a little snippet with my ide so i do access g as you can see it just brings up a little bit of boilerplate because i use axios all the time and so we wanted to call an endpoint and for our end points if we do let end point equals oops i've got the d again and i come over to here our end point is going to be the base url of the api that we're calling so this part here and so we want start with that and then we want to append our end point the part that our regular expression matches so in order to get that we just put rec dot params dot end point like so and if you notice i've actually knocked the uh forward slash off of this part because um our regular expression will actually match the forward slash so you don't need to put that in there and if you do you may actually get an error um so now we've got our axios get set up all we need to do is return it so it's a json response like so and then that will just be response dot data and then we can return an error just in case we get one of those which hopefully we will not so now we can take a look at this in the browser so if we come over to our server here and then just kill it and then restart it like so and let's go to the browser and at the minute our route would match foo so obviously that's not part of our api we actually want it to match public holidays 2020 gb and so if i paste that in like so and make sure that forward slash is in there and hit enter excellent we actually get the response and that's the json response and we've now avoided that cause issue that we got at the very start however even though our express server can access the api our view app still can't access our express server and to show you that i'm going to go over to our view app and i'm going to change this to localhost so and if i come back over to the view app which is here and i hit refresh we're still getting that network error even though we're looking at localhost 3000 so what we're going to need to do is we're going to need to install cause on our server so let's go back to the terminal and we want to do npm install cause and now that's installed we just want to use that in our project so const cause equals require cause and then we need to do app use and we use the cause function and we want to set the origin to this wild card and that basically says our server will accept requests from any other server and so we don't get concerned by any kind of cause issues from any other server so now we just need to reset start our server so let's just stop that and restart it and if we come back over to the browser and hit refresh ah it works so now you can see that we've bypassed those cause issues and we're now able to access this api from our front-end javascript code so that's our reverse proxy set up and it took us around about 10 minutes and we could stop there but one issue that we've got is that our reverse proxy only currently works for this api because we've got this hard coded so what we're going to want to do is we're going to want to remove this and put this into and set this as an environment variable and to do that we can use a package called m so let's come over to our terminal again and npm install dot m like so and now if we come back to our server we can require dot m dot config and the config will be a new file new file called unsurprisingly dot m and now we can set our api base url environment variable to our endpoints like so and if we come back over to app we can now just get rid of that and we put in process m api base url and it's found my id is founded for us so that's there and we'll come over and we'll just restart the server like say and if i come over and refresh you can see that it's still accessing our api and we can um just set any api any api route inside our environment file uh finally we're gonna actually look at a different api and i found one on the internet called the newsapi.org and if you have a look at the format it wants us to send our requests in and it actually wants us to pass things through the query string so we might pass a queue parameter a from parameter a sort by parameter and it also wants us to send through an api key our current reverse proxy server isn't set up to handle parameters or send parameters through so we're going to finish up by altering our code so that it can handle this api as well as the other api that we were using so the first thing we're going to want to do is we're going to want to set our api key in our environment variables file because we don't want to be passing api keys from our front-end javascript so if we come over to our environment variables file we want to put in api key and i'm just going to type in api key i do have an api key but i just don't want to display it on video and we want api key param name and what this is going to refer to is this part here which is the field name for the api key for this api it's called api key but for a different api it may for example be called key so we just want to set that so we can change that if we want to use our reverse proxy server for a different api so now we've set our api key and our api key for ram name we want to come over to app.js and the first thing we're going to want to do is we're going to want to create a little object called params like so and then we're going to want to add our environment variable so process m and this one will be api key for ram name so set the api key for ram name and we want to set that to process m api key and once we've done that what we can do is we can then pass that through axios and it will build the query string for us so we don't have to do that and so all we need to do is pass in an object and then set params to our params object so that just refers to our params object there one of the things here though is that for our other api um we didn't need to send through an api key so we just want to check that that is actually set in our environment variables file so we can just do if the pram name is set and if the api key name is set then add that to our params object so we've now dealt with uh setting our api key but we haven't dealt with any of the other parameters we need to send through so here it wants a field called q and one called from another called sort by and one called publish that so in order to do that we can get the parameters from our request and we can loop through them and add them to our params object up here so to do that we just put four and then a nice little bit of es6 filled value so of object dot entries and that will be of our query string just mistyped misspelled value there and then all we then need to do is to put params filled equals value and now we've just added all of our um query string parameters uh to our api endpoint so that it's now going to be sent through um from our reverse proxy server before we can check this out in the browser we're just going to want to update a couple of urls so the first one will be in our environment file where we've still got our old api endpoint so let's just come over here and we're going to want to update that to our news api endpoint that's here like so and then we're going to want to update our api endpoint in our view app and that's just going to we're still going to be calling localhost 3000 but not this public holidays endpoint instead we're going to want to call um this section here we don't need to pass through the api key because our proxy server is handling that for us and so we just come to here like that and now our view app uh should call our news api endpoint correctly um so what we're going to want to do is we're going to want to restart our node server and check this out in the browser so let's just go to our terminal kill the server fire it back up and we'll go back over to our browser and our view cli app and let's just hit refresh and excellent as you can see we've now got our results from our news api so that's our reverse proxy server setup if you want to you can clean this code up a bit by refactoring this section into its own class but i'll leave that for you to do and if you enjoyed this video then please leave a like on it and if you're enjoying this channel then please subscribe i do appreciate it and thanks for watching and i shall see you next time
Info
Channel: CraigGoesCoding
Views: 3,344
Rating: 4.8125 out of 5
Keywords: Express, Node.js, Vue, JavaScript, front-end, web development, servers, proxy server
Id: 5jPoTpXpIH4
Channel Id: undefined
Length: 18min 25sec (1105 seconds)
Published: Thu Sep 03 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.