Coding

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

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