Parsing the Body & Handling CORS | Creating a REST API with Node.js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back to another video in this create a restful api with nodejs serious in this video will do two things we'll have a look at how we can extract the request body of an incoming request like let's say for a post request and we'll also have a look at how we can handle a course errors now for that will also see what course actually means and then how we can handle such errors so let's dive into both topics in this video let's start by extracting request bodies for that I quit note Mon for a second and I will install another package with NPM install - - save - all the story entry in package Jason and the name of the package is called body - parser now as the name suggests we can use this package to parse the body of incoming requests because it's not nicely formatted and easily readable by default in nodejs and we can then use that data and body parser does not support files for example but it does support URL encoded bodies and it also supports json data so if we receive a post request that contains json data now to use that URL at that body parser we should go to app j s and there at the top lists first of all import it I'll name this body parser and I will require it from body - parser like this then I will apply it to my incoming requests we already used the logger middleware Morgan right after it I'll use my body parser middleware and now the body parse or middleware there actually need some additional information which kind of bodies do you want to parse first I want to parse URL encoded bodies and there we should pass a JavaScript object where we configured this type of parsing and there we should set extended to either true or false true allows you to parse extended bodies with rich data in it I will set it to false to only support simple bodies for URL encoded data more interesting to us here however is the following body parser which will apply there after Jason as a method but without arguments and a link to this package with more information on it and all the configuration you can pass can also be found in the video description so this will now extract JSON data and makes it easily readable to us the same for URL encoded data we can now use this in our routes like here for that's when we post a new router a new product excuse me we could create a new product as a JavaScript object maybe with a name and I want to get that name from the incoming requests and with body parser there will be a body property where I then can extract different properties depending on which data I received so let's say I expect to get a request body which has a name property then I could extract it like this and how do I know if I have such a property on the incoming request well we as a API creator either are the user of the API anyways or if we intend to publish our API to four parties we should set up a documentation where we clearly state which data our different API endpoints need to work correctly and this is also what you will see for public API so they always have a documentation where they say hey for a post request to this resource we need this data and you will get back a response with this data so here let's say we expect a name and let's say we expect a price request body price and to confirm that I got this I will add a created product property to my response Jason and simply pass this product object along so that is my data for creating a product now for trading order I'll do the same I'll create my new order object and there let's say we would have a product ID and I would get this - from request body product ID and then maybe we have a quantity request body quantity something like that and here I will also return my order in the order property of the response JSON data now with that let's first of all run NPM start to bring up that server again and then let's try it out by posting two products and two orders so here first of all I'll post to slash products and now we need to send body to see something so in postman you can go to body here then you can simply switch between different types of body I will choose raw and now with raw I can go to the drop-down and pick Jason so now here we can create a JavaScript object which should be our JSON data I want to send there I want to set a name like Harry Potter five and keep in mind for products we also extract the price so I also get the price here and we can discuss if it makes sense to receive the price from the user who may alter the request but this is not the final state of the API no worries so here the price could G be $12.99 let's now hit send and we get this strange error now what's wrong here well what I'm sending here is not valid JSON data for valid JSON data we must only send string data so we should enclose the property names between double quotation marks and also the price and now if we try this again we indeed get back handling post requests to slash products and to create a product with the data we submit it now let's try the same for orders there I if you have a look at the URL or at the router I should say we extract Product ID and quantity so let's pass these two parameters or these two information pieces product ID can be this ID and the quantity quantity could be let's say 10 and now if I had send we see that this was successfully created and we get back that data so parsing the body does work so we made sure that we can parse our request body let's now work on something else fixing course errors we haven't seen any but you if you've worked on any single page application anything like that you might already have seen these course errors they look like this simply search for course error on image search no access control allow original header is present on the requested resource this is what you typically see that now what does this mean what our course errors about what is course to begin with course stands for cross-origin resource sharing and the idea behind it is pretty good it's a security concept we have a client and a server and if both are coming from the same server so if the client if the page you're on is served by the server you are sending a request to let's say you have a traditional web app where you get back HTML pages and on one page you use jQuery HX or some other Ajax library to send some date or get some data there on the same server then this will just succeed because then you're trying to access resources on your server from that server now for a restful api this is never the case instead client and server typically have different URLs different origins and even the port number on localhost is considered a different origin if it's not the same in this case trying to make a request to a resource on the server will fail because as a default the browser is saying it doesn't make that much sense for you to get something from that server it's not the server you are coming from now that's a security concept but for restful api s-- we want to allow this axis because restful api s-- are meant to be consumed by our clients by our servers and not just by the server the api runs on that wouldn't make it dead useful because keep in mind we don't serve an application from that api we just serve data therefore we can overcome this we can basically disable this mechanism by sending some headers from the server to the client that essentially tell the browser which is running our client application which tell the client yeah it's okay you can have access and then the browser says okay so here you go so what we have to do now is we have to ensure that we send the right headers back and how do these headers look like let's go to the App J's file and there I want to basically append the headers to any response we sent back so we should do it before we reach our routes here because there we do sent back a response so before the routes I'll add another a middleware with app use to funnel every request through it and there I'll use my arrow function which receives the request response and this next object and in there I now want to add some headers to the response this will not send the response it will just adjust it so that wherever I do send a response it has these headers so with response header I add a new header and then the first header I need to set as access - control - allow - or wretched remember that course error message it said no access control allow error origin header is present well now we set it so it will be present this header also needs a value and the value can be start to give access to any origin you could also restrict it you could say only HTTP my cool page comm should have access but typically for restful api as you give access to any client because you really want to narrow it down to one now the next header or one more header we need to add is access - control - allow - headers to essentially define which kind of headers we want to accept so which headers may be sent along with the request you can also set this to a star to allow anything you could also set this to a rich in X requested with and maybe content type and maybe accept and maybe also authorization so that all these headers can be appended to an incoming request I will now also check if the incoming request method method is a property which gives us access to the HTTP method used on the request is equal to options browser will always send an options request first when you send a post request or a put request this is basically something you can't avoid where the browser sees if you can't make this request if he's allowed to do so so you send the options request first for this case I also want to add an additional header where I tell the browser what he may send so I will add access - control - allow - methods and set this to put post patch delete oops patch delete exiting out of the string so like this get basically all the requests or the HTTP words you want to support with your API now if we have such an options request I also already want to return response status 200 with a JSON data load or payload but that actually is an empty object because here I don't need to go to my routes because the options request is just for finding out which options we have and by sending back a response where we add all these course headers we do provide such an answer for our methods only the first two headers are attached and that's all we need and thereafter the request may continue so that's the idea behind this setup it ensures that we prevent course errors now one question remains why did we never encounter course errors when we use postman the answer is postman is just a testing tool it's not a browser and keep in mind that I said that course arrows are a security mechanism and forced by the browser that's why you can override them with headers the browser then knows to ignore that well postman just doesn't care stare for testing this also has a whenever important application if you ever thought about protecting your API against unwanted access by restricting the allow origin to maybe your own domain only this will work for webpages our web pages won't be able to use your API with that but you can still get access with tools like that so it's not really a protection mechanism when it comes to debt but you can ensure that our webpages contacts is your API still here I provide access to everyone and with that setup we shouldn't encounter any course errors when we connect a single page application or some average client to our API now with that we added course error handling but right now we would always block our incoming requests we also need to call next the end of our middleware if we're not returning immediately due to us getting options requests so that the apparatus can take over so with that let's make sure to also start node Mon and it should then automatically restart you can still send requests and you could now also send them from single page applications and so on now with that we added body parser we're handling course errors now I'd say in the next video it's time to finally add a database and then do some more useful things on our server
Info
Channel: Academind
Views: 200,672
Rating: undefined out of 5
Keywords: node, nodejs, rest, restful, rest api, tutorial
Id: zoSJ3bNGPp0
Channel Id: undefined
Length: 15min 52sec (952 seconds)
Published: Fri Dec 08 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.