Node.js Crash Course Tutorial #10 - Get, Post & Delete Requests

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
our ivan gang so far in our website we've made only one type of request and that is a get request and we've had handlers for those get requests when we've said things like apt-get now these types of requests are typically to get a resource from the server whether that be JSON data from the database or a webpage doesn't really matter they are all get requests but there's other types of requests too so we have get request to request data from the server we also have post requests to create new data in our database so typically when we have a webform and hit submit then we send a post request to the server with that new data and it can be added to the database we also have delete requests to delete data for example deleting a single blog document from the database and we also have put requests to update existing data now so far we've seen how we can send get requests from a browser and handle those on a server for example we have this route forward slash blocks that is a get request and that gets us a web page with a list of all of the blog's inside it we also have a get request for forward slash blogs forward slash creates and that gets us a web page with the web form on it but we also need routes to interact with our data in other ways for example we need one to add a new blog document after we've filled in the form and then hit submit so that needs to send a request add a new blog and that would be a post request now the route would be forward slash blogs the same as this one up here so how can that be well that's absolutely fine because this is a get request and this is a post request so we can use the same routes for different types of requests because get requests and post requests can be handled differently from each other on the server so that's fine so when we click on submit on our web form we're going to send a post request to this URL and we're going to handle that on the server to add a new documents to the database now we'd also need a route item to get ace single blog item and that would look like this forward slash blogs for /id where this ID variable right here changes dependent on the blog that we want to get so it would go out and get the blog from the database with this ID and that would be it gets requests now another route for deleting a blog would look something like this forward slash blogs /id and again this would be the ID of the blog we want to delete and again these are the same but it doesn't matter because we can handle a get request separately from a delete request on the server finally you might also have a routes for updating blogs and that would look something like this as well well we have the ID that changes but that would be a put request so this route structure is the typical structure of a simple crud application for every different data type or resource we have for example blogs users books authors whatever the resource type might be it might look quite similar to this kind of structure of URLs and types of requests so in our application we're not going to use the put request we're not going to update blogs but we are going to do the rest now you've already handled these two at the top forward slash blogs to get the index view with all of the blog's embedded in it we've handled this request forward slash blogs forward slash creates which gets us the web page with the web form on to add a new blog so we need to do these three now a post request to add new data to get request to get a single blog and a delete request to delete a single blog let's look at the post request first of all alright then so imagine you're a user on this website and you want to add a new block then I'm guessing you would go to new block he'd add in a load of junk and then you click on submit to add this new exciting blog to the websites now at this point we need to fire a post request to the server with all of this data included in the post request then on the server we can handle that post request we can take all of that data create a new instance of a blog document using the blog model we created add this data to that instance and then save that document to the database so that's the sequence of events that needs to occur so the first thing we need to do is send a post request from this webform when we click on submit now there's a couple of ways we can do that we can do that using the fetch API or some other asynchronous library from JavaScript or we can do it directly from the webform itself so we're going to do it from the webform itself and to do that we need to open up our create view and all we need to do is add a couple of things right here so inside the form tag we need first of all an action attribute and that is basically gonna be a value to where we want to send this request to well the URL for this post request is going to be two forward slash blocks right we saw that in the different request URL chart we saw before so we also need another attribute and that is going to be method and that is the request method so this is going to be a post request now when we click on submit this is going to send a post request to this URL or right here now we also want it to send all of this data and attach it to the body of the post request so we can access that on the server and to do that we need to add name attributes to these input fields so the name of this one is just going to be the same as the ID probably the title the name of this one is going to be the snippet and the name of this one at the bottom is going to be body ok so then when we access the form data on the server we'll use these properties to access that form data all right there so that's all we need to do so when we click on this button now it's gonna send this post request now we need to handle that on the server so what we need to do is first of all come down to blog routes over here and I'm going to create a post handle so to do that we say app dot post so before we handled get requests now we're handling a post request so app dot post and we want to scope this to forward slash blocks that's where we're sending the request to right here and then we want to fire back a callback function so let's say request and response and inside we want to save a new blog documents to the database but we need access to all that data that comes along for the ride in this post request when we click on submit this data this data and this data so how do we get that well first of all we need to use a bit of middleware which is going to pass the data that we send in to a workable format that we can use and it's going to attach it to this request object so I'm going to come up to where we use some middleware and below the static middleware right here I'm going to paste this in so it's middleware that comes along with Express so we say app don't use Express dot URL encoded and then we say extended is true inside we don't need to do this this is just an option that you can add in so this basically takes all the URL encoded data that comes along for the ride and it passes that into an object that we can use on the request object so down here inside this post request handler we can now access request body and that contains all the information we need from the webform let me just log this to the console so I can show you request body like so and we're going to open up the console down here okay let's send a request now so if I go over here and just click on submit then it's going to reload the page that's the default action of a form when we click on submit we'll sort that later but if we go over here we don't anything logged to the console and that's because we actually need to refresh this page to catch the front-end changes we made over here so schoolboy error let's refresh the page and let's add in a lot of stuff again submit and now if we go back over here we can see this object right here we have the title the snippet and the body so all of that now is attached to request body and that's because we used this thing or right here okay if we didn't use this right here let me comment that out and let me come over here again if we try to submit this again let me refresh over here continue let me just go back in fact this would be quicker okay if we try to do this again add in a lot more data submits then come down here it's undefined so we can only do this stuff where we get the request up body if we use this middleware right here okay and that's for accepting form data so let me save that now and now down here what do we want to do with this data well really we just want to save it to the database but first of all we need to create a new instance of a blog so let's do that let's say Const blog is equal to new blog and we pass in an object with the different properties remember but that object looks very much like this object right here so all I need to do really is just say okay well request body then we're passing that object in which is this thing right here so we're creating a new blog with a title snippet and body and that's all we need to do so now we have that we can say blog save to save this to the database it's asynchronous returns a promise so we tack on dot then and fire a callback function when this has done so we can take the result here just in case we use it in the future but at this point what do we want to do after a user has clicked on this button right here yeah and it submits that to the server we save that to the database what do we want to do then what do we want the user to see well I'd like to redirect them back to the home page so they can see that new blog right here on the list so all we need to do is say response dot read rekt and we're going to redirect to forward slash blocks which is where all the blocks are listed so we also can attach the catch block right here which catches any errors if there are in it and then we can log that to the console for now like that okay so let's see if this works I'm going to go to add a new blog first I need to stop that request go to add a new block the block title is gonna be like Yoshi is party and the block snippet is come and have a good time Wow sounds amazing let's just put in a lot of rubbish here okay so submit this and now we get redirected to the home page once this is done and now we can see that new document right here and if we go to the database and we refresh over here we should see that new document here as well which we do right here awesome okay then so now we've handled these three routes right here we still need to do these two right here one for a get request to get a single blog and one is a delete request to delete a single blog now to address those we need to learn about this part of the route right here and they are called route parameters shurl then what are routes parameters well around parameters are the part of a route that are variable or could change in this route for example this part in green the ID would be variable and it could change dependent on the blog that we want to get so for example we could go to forward slash blogs forward slash one two three four five and this right here would be the route parameter or forward slash fifty and this would be the route parameter it could even be /hello it doesn't have to be a number we're not setting up rules we're saying here that this part of the route is changeable it's like a variable that a user types in and we want to be able to extract this to see if it's an ID and then we can query the database for the document with that ID and send it back to the user so we need a way in Express to extract a ramp parameter from a URL so it can use it okay then so there's a couple of things I want to do here with route parameters the first thing I want to do is surround all of these with links so that they go to forward slash blogs forward slash the ID of that particular blog now remember each blog document has this ID and when we use Mongoose it converts this into a string for us so this ID property at the top right here we have access to inside our index view on each blog because we go out we'd get all of the blogs and we're passing those into the index of view and we have that underscore ID property on each blog right here so what I'm gonna do is actually surround the h3 and the paragraph tag with an anchor tag so let me do that first of all and put the closing bracket at the end so /hey okay and let me just explain what this is doing so we are now surrounding this with an anchor tag to forward slash blogs forward slash and then what outputs in a dynamic variable which is on the blog and that is the ID so it's going to be forward slash blog forward slash whatever the ideas for that blog I've also given this a class of single for CSS and we'll do that later but for now let's save this and go over to view this in a browser I'm gonna refresh and now if we click on one of these for example we go to forward slash blogs and then forward slash the ID of that blog now it's going to change this ID dependent on what blog we click on all right so now we need to handle this request right here it's get request to this URL forward slash blogs forward slash the ID so we need to now extract this route parameter from the URL in a request handler so let's set that up so over here underneath the post request will do this so down here I'm gonna say app gets and it's gonna be for forward slash blogs forward slash and then to denote a ramp parameter we use : an ID if we just said for example ID then it's going to look for /id literally not an actual ID so there needs to be a colon in front of whatever you want to call the route parameter alright so then now we have that we need a callback function we're taking the request and the response object as always and inside this function I want to try and find a single document in the database with this ID but first of all I need to extract this ID well we can get that from the request object so I can say Const oops Const ID is equal to request then we use the param property and then we use the ID so whatever we called it right here if you call this nuts then you'd say params dot nuts all right it makes no sense so let's stick with ID all right so we have the ID let's just log this to the console to make sure it works console log ID all right open up your console and then let's try this out go back and click on one of these and it's gonna hang because we're not sending a response but we can see the ID are logged to the console so we know that works we've got the ID now we need to retrieve the document with this ID from the database so we use the blog model capital B remember then find by eye d and we're passing the ID right here this is asynchronous take some time we tack on the then method and we get the results in a callback function now what do we want to do with this results well ultimately we want to render a details page so we need to create a details of view shortly but let's just set this up for now render and it's going to be called details this view and we want to pass through the data that we get back so the block is what we'll call it but you can call the property anything you want and that is going to be equal to the result because this result will be the single blog based on this ID we also need to send in a title like every other route we have a title right and the title for this page is going to be blog details like so so that's what we're doing in the then method after we've got the blog we send it into a view which we're going to create in a second first of all let's catch any errors if they are in it and just log those to the console all right sorted so now we need to create these details of view right here so let me go over to views and create a new file called details ejs and in here I'm just going to pay some HTML code in it then explain it so you don't have to watch me write it out from scratch so we open up the HTML tag we include the head partial like we do in the other views we include the nav partial at the bottom we include the footer 1 as well this is the actual content we're concerned about now remember inside here we pass through the blog which is the results so the blog object so we have access to that right here and we have a div with the class of details and contents then we have this blog object and we access the title property on the blog which we have under that we output the body property as well inside a div and a paragraph tag at the bottom we've got this anchor tag right here which is to delete a specific blog or later on so don't worry too much about this now in fact I'm going to delete this for now so we're not worrying about it and just save it like that so we're just outputting the blog title and the dog body right dead simple so we're sending that details of you back let's save this and see if it works so let me come over here and go back and then click on one of these Yoshi's party and it should work but I think it's not doing okay let's see if we get an error render is not defined okay sorry we need to say response don't render right here so save that and go back let's try this again new blog - and we still get some kind of error so let's have a look okay not working juicy yeah okay so there was just a lag I think and it does actually work so if we click on one of these again yep we see the title and the contents and if we click on a different one we see the title and the content awesome now I do also just want to add a couple of styles to this page right here so let me just go to the Styles inside the public folder and I want to scroll to index tiles and I'm gonna paste these things in or right here so just two things so blogs a which is this thing right here anchor text surrounding each blog what I'm doing with that is saying display that has blogged give it a bit of margin padding left and then a border left which is crimson like a red color and when we hover over those the h3 which is the blog title the color of that text is going to be red as well just makes it look a bit better so let's refresh this and there we go that's all working so now we have our details page sorted rather than gang so we are slowly getting there the only route left to do is this one right here which should be a delete request to delete a specific blog document and again we're going to have the same route structure as this one right here where we use a routes parameter this time though we need to send a delete request and handle that instead of a get request so let's do that now so then we want to be able to delete blogs from the front end and we could do this from a delete button or link on each blog details page so if we click on a specific blog maybe we see a Delete icon somewhere we click on that that sends a delete request to the server then we go out to the database from the server and delete the blog with that ID all right so before we do anything we need some kind of button or something to click to send that request so back in details I'm just going to paste back in the anchor tag that we had right here we give this a class of deletes and we give this a data attribute now this is a special attribute inside HTML where we can basically add our own custom attributes I've called this doc so we say data - then whatever we want to call this attribute and I've set this equal to a value and this value is going to be the blog ID that we want to delete remember we have access to the blog in the blog details page so we're just getting the ID of that and storing it in this custom data attribute so that when we click on this we can grab this data in some JavaScript down here and using the fetch API we're going to send a delete request to delete that document with that ID so before we do anything let's save this and look at it over here yep looks absolutely pumps so let's just add a little bit of CSS so in the detail Styles I'm gonna paste in a couple or rather three styles so first of all the details class which is this thing right here the div surrounding everything I'm saying that is going to be position:relative and I need to do that because I'm positioning the delete anchor tag absolutely relative to this okay so we say we want this to be in the top right the border radius is going to be 50% of this thing that curves the corners so it looks a bit more like a circular kind of button the padding is 8 pixels then delete hover which is the hover effect we're going to say the cursor is pointer of the little hand and give this some box shadow so let me save this and preview again and now we see this thing over here all right so we will make this maybe an icon later so it looks better still because to be honest it still looks pretty pants put nonetheless when we click on this now we want to send a delete request to the server now we're going to do that in vanilla JavaScript on the front-end so important to notice this is not gonna be JavaScript that is running on the server this is going to be running in the browser and when we click on this because in our view over here if we add a script tag for example at the bottom if we do this any script inside this script tag is going to run in the browser when it reaches the browser not on the server okay so we're gonna run through this really quickly because this is not a front-end JavaScript course and as I said you should already understand about front-end JavaScript asynchronous code and all that kind of just if you want to learn about that i've got a free modern javascript course on the youtube channel and a premium one on udemy the links to both of those are going to be down below so I'm gonna first of all get a reference to this thing to do that I'm going to say Const and we'll call it trash can even though it's not a trash can yet but we will maybe use a trash can image later on and I'm going to set that equal to document dot query selector to grab this element and we're going to grab a dot delete so it has a class of delete so we're going to grab this element so we have a reference to that now so now we need to add an event listener to this so we can detect when a user clicks on this so to do that I'm going to say trash can dot add event listener and that event is going to be a click event so click and then we fire a function where we take the event object as a parameter and inside we want to send a delete request now to the server and we're going use the fetch API to do that but before we do that where are we going to send this request to well we'll store that inside a constant so we can reference it later and we'll call it endpoints and set it equal to a template string which is backticks that's below the Escape key on most keyboards so this is going to go to forward slash blocks forward slash and then we want to output a variable now this is going to be the ID right so we can get that ID from this attribute right here and the way we access that is by saying trash can which is our reference to that element dot data set and that's anything that uses this data attribute then the name of this thing right here so dot doc because that's what we called it all right so this is the endpoint so it's going to be forward slash blog forward slash whatever the ID is right here so we want to send a delete request to the endpoints how do we do that well we use the fetch API and we specify that we want to send it to the endpoint and that's the first arguments and then we pass in an object and this is like an options object for the fetch API to say what type of request we want to send etc the only thing we need to say is the method which is going to be a delete request so before we had a post request we've also seen get requests now the method of this is a delete request so that's it it sends out a request now from the JavaScript to this endpoint with that blog ID in it and it says that this is a delete request so when it gets to the server then we know it's a delete request and we can handle it as such alright then so this right here is asynchronous and we can attach a then method to it so when it's done it's going to fire the then method so I'll do that I'll say dots then and we'll fire some kind of function and we'll come back to this later in fact let's just do this for now and we can also attack on a catch block to catch any kind of error and then we'll just log that to the console if there is an error okay so again if this was all over your head then definitely check out my modern JavaScript course first of all to understand all of this okay then so now we're sending this when we click on this button we need to handle this on the server so let's go back to our app JS file and we need now a handler for the delete request so let's do that down here I'm going to say app dots delete this time to handle a delete request this is to the same route as this so let's copy and paste that all right here then we need a callback function when this request comes in so we take the request object the response object and over here inside this function we want to say first of all the ID so Const ID is equal to the request params dots ID remember that's how we access the rat parameter so we have that ID now we can use the block model to say we want to find by ID and delete that is the method we use and we just pass in an ID which is the ID we get from the route parameter so this goes out to the database it finds a record or a document by the ID and it deletes it from the database again asynchronous we tack on the dot there method and we take the result and what we're going to do here is send back some JSON to the front end the browser now why are we not redirecting here well when we send an ajax request which is what this is because we're doing it from javascript we're not doing it from a webform or anything like that this is an ajax request when we send that type of request in node we cannot use a redirect as a response we can't do that we have to send maybe JSON or text data back to the browser okay so what we're going to do is actually send some JSON data back to the browser and that JSON data is gonna have a redirect property right now when we receive that data back over here we're gonna look at that redirect property and that read our it property is gonna be a URL to where we want to redirect to and then that's going to be done from the front end because we can't do it on the server because this is an ajax request a hope that makes sense it might seem long-winded and around the houses and but this is the way we're going to do it so if i go back to a pas what I'm gonna do inside here is say response and the way we send some JSON back is by saying response Jason now this is the typical response we'd use for an API where we can you know reach out with JavaScript to get data or delete data and all that kind of just so that's the reason I'm doing it this way I want to show you how to do this so response Jason and in here we're gonna pass an object and the redirect is going to be to forward slash blogs so what we're saying is after this is complete when it's deleted up then come back here and we'll send a response to the browser it's gonna be adjacent object and we're gonna pass that on the front end or look at this property and say okay well I'm gonna read our it myself in the browser to this URL and it will do that for us okay now before we do that all let's tack on the catch method right here so we can take any error if there is one and log that to the console so console dot log error cannot type okay so let us now save that and go to the front end so over here when all this is done and the response here is sent to us then we get that JSON back inside here and we get that JSON back as Jason which we can't readily use so we need to take that JSON data so let me just say this is going to be the response right that's the JSON data that comes back to us and right here we need to use a method on that so we say response dots jason we can use this right here and what that does is return another promise whereby it passes this JSON data into an actual JavaScript object that we can use so I can check on another their method where we get access to that actual JavaScript object which I'm going to call data and I'll tell you what we'll do for now is we'll just log that to the console console dot log data so this right here we don't need a semicolon this right here should all work we click on this it sends a request to the server the server deletes that document based on the ID it sends Jason as a response in this thing right here we take that jason we pass it into a JavaScript object which we can use and we get access to that right here and then we're just logging that to the console okay save it and let's refresh and give this a whirl I am gonna cross my fingers because that was a large amount of code we did and I'm hoping we don't get an error so all let's try this deletes and yes we get this back ok so we get this object back now if we go back over here remember new block to that shouldn't be there so it's been deleted it's no longer in the database if i refresh this we should see two instead of three now which we do awesome so that is all working so the only thing left to do now is to redirect on the front-end instead of this console log because that's not very useful to a user so how do we read our it from the front end well we take the window object and we say dot location and then we say dot H ref and we set it equal to where we want to go and that's going to be the data that we get back dots redirect that was the property attached to that data object if we take a look over here no we don't get that response anymore if we take a look over here we can see that was the property right so now when we get this response back hopefully we should redirect back to the blog's page so let's try this once more time delete it it deletes it redirect us awesome all working and now my friends we have handled pretty much everything we need to do we've got get requests post requests and delete requests going on so now I want to move away from this and in the next video I want to talk about MVC and the Express router just to tidy everything up a bit
Info
Channel: The Net Ninja
Views: 90,272
Rating: undefined out of 5
Keywords: node.js, node, node js, node.js tutorial, node tutorial, node js tutorial, node crash course, node.js crash couse, node js crash course, crash course, tutorial, install node js, install, node.js introduction, what is node.js, what is node js, what is node, node vs deno, post, post requests, node post requests, node.js post requests
Id: VVGgacjzc2Y
Channel Id: undefined
Length: 33min 37sec (2017 seconds)
Published: Thu Jun 25 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.