Node.js Crash Course Tutorial #10 – Get, Post & Delete Requests
- December 26, 2023
- Posted by: MainInstructor
- Category: Go JavaScript Node
Video Title: Node.js Crash Course Tutorial #10 – Get, Post & Delete Requests
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
-
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
Can some explain why we can't use res.redirect('/blogs') inside the then of findByIdAndDelete ?
like
app.delete('/blogs/:id',
(req,res)=>{
const id = req.params.id;
Blog.findByIdAndDelete(id).then(
// (result)=>{
// //.json sends the json passed inside to res
// res.json( {redirect: '/blogs'});
// }
res.redirect('/blogs')
)
});
with just fetch api call in the <script> tag, no need for .then there.
Bit elaboration on the ajax thingy which shaun was saying there.
Note that u need to write the app.get('/blogs/create') above app.get('/blogs/:id') otherwise u might get these errors
BSONError or CastError: Cast to ObjectId failed
Loved the content. Gave me great learning over the weekend. I loved how he builds the pieces early on and how they all come together at the end to form an application. Not only gives you the details on how it can be done, but also why things are done the way they are done. Loved it. Huge thanks.
i checked many time the button is not working at all
I have a question about those dynamic routes like /blogs/:id . What happens if you past incorrect id? Then your code will try to find incorrect id in the DB and throw an error? And then you'd handle that error by redirecting to 404? Do I understand correctly? Coz I used to struggle with React Router while trying to implement routing only on the front end…
Thanks
I've recently started this tutorial series and I bet it's the most valuable tutorial even among the paid ones
is there an example of making an update route path. I don't know if I am on the right track with the one I made.
nevermind 😀 I just figured out how to do an update method for my crud application. also thank you for the course. You are literally one of my top sources to go to when I am interested in learning more for the frontend in my full stack journey.
your videos help me sm man
thankl you for make uni a little easier for me
Nice tutorial for real !
Thanks for your good work, more blessings man.
but I'm getting this bugs when I want to go to my create page "BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer"
Hoping for your response.
my css doesn't work wherever there is /blogs/… and shows error of styles.css not found
when i change it to just /… it works fine
can someone help
Nailed it. U r legitimate Ninja
19:04 it brings me a BSONError
Thanks so much for this course. It's so amazing. can you please consider implementing image uploading with node express and mogodb.
I think I lost my way. My page shows, in plain text: "Home Your path to becoming a Node.js ninja!"
I CTRL C to stop Node, download and paste Lesson 10 into node-crash-course, type nodemon tuts in my terminal, but the webpage still has the text and style from one of the earlier lessons. Doesn't look anything like the output in this lesson. UPDATE: Not sure which lesson I got "nodemon tuts" command from, but I stopped the server, then typed "node app" and now my blog is looking correct again.
I know I'm two years late to the party but I get SyntaxError: Unexpected token '<', "<!DOCTYPE "… is not valid JSON during the "delete" portion of this. Anyone have any tips?
CastError: Cast to ObjectId failed for value "styles.css" (type string) at path "_id" for model "Blog"
If u face this problem, then go to views/partials/head.ejs and edit the css path.
Could we not make the button into a form tag and instead of a post request we add a delete request
?
Even though these videos are long, there is not one second of fluff. Beautiful.
thanks
Great course but the delete solution was bad. Super easy way:
blogPost.ejs –
<form method="POST" action="/delete/<%= _id %>">
<button type="submit">delete</button>
</form>
server.js –
app.post("/delete/:id", (req, res) => {
Blog.findByIdAndRemove(req.params.id)
.then(() => {
res.redirect("/");
})
.catch((err) => console.log(err, "error"));
});
Can you show how to update the data?
Because I can’t get the data after I submit it. (PUT method)
Thank you in advance.
Guys, if you get an error around 19 minutes I may have a solution
in the app.get function for this function /blogs/:id
console.log the id.
[EXPLAIN]
If there is a space at the start of that id for example " 234f23424f223423c"
This string wont be a valid ObjectId string, so it can't be casted to a ObjectId Object.
[QUICK FIX]
app.get("/blogs/:id", (req, res) => {
let Newid = id.replace(/s/g, "");
Blog.findById(Newid)
[REAL FIX]
you need to find where you created the id and all references of id in your code and remove the space.
Hi! I had to trim the id with the trim method to pass it to the Blog model, did i do something wrong or there was a change on how the string from mongoDB is returned?
After A whole year of my previews comment I still see the delete part the most complicated
I have been getting this error:
CastError: Cast to ObjectId failed for value "style1.css" (type string) at path "_id" for model "Blog"
Can someone help me ?
good job , it 's verry helpfull
title: CastError: Cast to string failed for value (type Array) at path "title" Can someone say about this?
Hi gang! I have an error: min 31:57
SyntaxError: Unexpected token '<', "<html lang"… is not valid JSON -> .then(data => window.location.href = data.redirect)
.catch(err => console.log(err));
});
The error that the console displays is as follows: Failed to load resource: the server responded with a status of 404 (Not Found)
It seems that it's a problem with the catch method and I've already tried everything that google can offer (stackoverflow and etc). Can some one help me? I really am enjoying this course and wanna finish it. Thank you very much!
Shaun you are a legend. I am in the middle of an intensive assessment for a position currently and everytime I run into a problem, be it in Vue, node js or SQL you seomhow seem to have the answer at some corner or the internet. Keep up the amazing work!
Great tutorial, is there an example of put request with this type of logic?
Hi mate,
How could I use the contents of a div with the contenteditable="true" instead of a textarea? I would like to put a WYSIWYG app in there, but it always crash.
Cheers,
Please help me
I got error in delete operation
When click delete in console show
"Unexpected token ' <' "<!doctype…is not valid JSON
I had to use `app.use(express.urlencoded({ extended: true }));` to not get: body-parser deprecated undefined extended:
CastError: Cast to ObjectId failed for value "style.css" (type string) at path "_id" for model "Blog"
I am getting this error please please guide
// If you get error around 19:11, which looks like this:
CastError: Cast to ObjectId failed for value "style.css" (type string) at path "_id" for model "Blog"
// Then simply remove <%- include('./partials/head.ejs') %> from details.ejs
// I don't understand why, but with only this:
const id = req.params.id;
console.log(id);
// id looks fine, but when you add this below:
Blog.findById(id)
.then((result) => {
res.render("details", { title: "Blog Details", blog: result });
})
.catch((err) => {
console.log(err);
});
// another id shows up in console:
6308f2bbcb373829482ab874
style.css
// Is anyone able to explain this?
Hey, I was having sort of an error when I defined the app.get('/blogs/:id') before app.get('/blogs/create') as for no reason it was treating 'create' as an id
however it works when I define the blogs/create above.
oooh fetch methods? async await?
Oooh my head hurts now! Content is excelletn as always but definitely need to play this one again!
why does he put 21:46 blog._id why not blog.id why the _??
the delete thing didnot work and the problem is i dont see the error thing in console wtf…….. i dont fking understand why 1000000 step for just delete thing ????!!!!!!!!!!!! is this what really delete takes ??? and help someone facing same problem
MongoAPIError: URI cannot contain options with no value
at C:UsersyashgOneDriveDocumentsnodejs-coursenode_modulesmongooselibconnection.js:796:16
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (C:UsersyashgOneDriveDocumentsnodejs-coursenode_modulesmongooselibconnection.js:793:19)
at C:UsersyashgOneDriveDocumentsnodejs-coursenode_modulesmongooselibindex.js:378:10
at C:UsersyashgOneDriveDocumentsnodejs-coursenode_modulesmongooselibhelperspromiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (C:UsersyashgOneDriveDocumentsnodejs-coursenode_modulesmongooselibhelperspromiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:UsersyashgOneDriveDocumentsnodejs-coursenode_modulesmongooselibindex.js:1223:10) {
[Symbol(errorLabels)]: Set(0) {}
}
[nodemon] clean exit – waiting for changes before restart
nice job mr net ninja , but honestly speaking I've been trying this delete request on my app but its not working and I'm really depressed right now
Hi Sir, You are doing code , code and code, not able to get the things
Could you help me.
How can i add image to this blog?.
I tried Multer,but i couldn't display image
Master Ninja, how did you learn all these stuffs?
You are really really good.