Parsing the Body & Handling CORS | Creating a REST API with Node.js
- January 5, 2024
- Posted by: MainInstructor
- Category: Go JavaScript Node
Video Title: Parsing the Body & Handling CORS | Creating a REST API with Node.js
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
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
Thanks for sharing such knowledge to us. I am so excited of watching this course. I have another question related to this lecture. I am so confused about CSP. I tried a small project to practice. actually, I used axios for my front-end, when I fetch the data, on my browser console, content security policy is blocking my localhost, I do not know how to handle with this issue. by the way, thank you very much!!!
{
"error": {
"message": "Cannot read properties of undefined (reading 'name')"
}
} getting this error
Is there a previous video required?? No idea what you already have setup going into this video…
god, it feels SO good when you're watching a tutorial video and you can simply understand everything is going on without pausing and going back, even if it's the first time I see it. What an awesome instructor, im pretty luck to have found you 🙂
Agreed with the comments. I've been having troubles understanding creating rest APIs and these tutos are just heaven sent!
Bookmarking 7:00
been surfing the internet for an explanation on how to work with CORS for hours now, and you my good sir, was the only person who actually explained it in a comprehensive and digestible way. Also the quick and concise explanations mixed with the beautiful face make the whole learning 100% easier, Thanks man 🙂
thanks man, but I really follow everything you have done still getting error in postman when apply post or get like: couldn't get any response could you tell me why or give me alike for GitHub code so i can replace it with mine and see why
Thanks a lot sir.
Champioooooooon!!!
That was amazing!!!!
best teacher and way of teaching is excellent
I've used a lot of different youtubers, website tutorials, and even codeacademy. I'm not sure what you are doing different but it's finally actually going in! I think it's because you don't bloat the tutorial with unnecessary extra technology. And you also explain the purpose of everything you write. But this has definitely been the best tutorial on Node JS that I've watched. Thanks a lot!
body-parser has been deprecated in my app
thanks man
No Hate But, The Code You Are Writing Is Unnecessarily Long For Ex: You Can Directly Create An Express App, Also Then You Won't Need To Import Router
Not work now.
I really love this serious(series).
Man… you are the best! Now, in 2021 this is the best course I have watched.
5:00
It's a good tutorial, but you don't explain why you put this headers 11:20
And maybe "Accept" and "Content-type".
Why don't explain that?
¡Thank you so much! Just what I needed.
Body parser is deprecated. What should i do?
Why do you use sometimes double quotes and sometimes single quotes? Is that equivalent?
JSON data can include; numbers, booleans, objects, arrays and strings null (not undefined).
Not just strings.
This is the best, clearest, most simple explanation I've come across (and I've watched a lot of them!) Thank you for this.