Node.js Crash Course Tutorial #11 – Express Router & MVC
Video Title: Node.js Crash Course Tutorial #11 – Express Router & MVC
A rather than gang so if we take a look at this app.js file at the minute it’s getting quite long there’s a lot of code in it and before long it might start to look a bit messy and hard to maintain and updates so what we’re gonna do now
Is explore a couple of things the Express router and also MVC which we’ll talk about later just to neaten this over maybe split our code into different files so first of all the express route it so the Express router is something that come was fully baked into Express
And we can use it to manage all of our routes more efficiently and more tightly as well especially as the size of your project grows and grows and you’ve got many different routes so we use the Express router to split our routes into different files and manage them in small
Groups of routes that belong together and it makes the app more modular and it also becomes easier to update those different parts of the app later on and it will mean that we don’t have to have everything justified in one big messy file so if we take a look at all of our
Routes from the top a lot of them have this init forward slash blogs forward slash blogs blocks blocks so these are all the blog routes right so we could split them into their own route file because they’re all concerned with one type of resource and they kind of belong
Together so let’s create a new folder to do this over here I’m gonna say this follow that will be called routes and inside I’m going to create a new file called blog routes because this will contain all of the blog routes now the next thing I’m gonna do is grab all of
The blog routes so from here I’m gonna cut all of these from this file so this file is already looking a bit tidier because we don’t have those and I’m gonna save this and paste them in or right here so now all of those routes are in this file now obviously at the
Minute this is not going to work because we’re trying to attach all of these around handlers to this app instance which we have bought this app instance isn’t defined and set up in this file it’s way over here in up jas so instead what we’re going to do is a couple of things
First of all we’re going to require Express so let me say Const Express is equal to a require and we want to require the Express package the next thing I’m going to do is create a new Express or router so I’m going to say Const router and you can call that
Constant whatever you want and I’m going to set that equal to Express dot router with the capital R and that creates as a new instance of a router object so what we can do now is we can attach these request handlers to the router instead
Of the app so let’s replace all of the earth times we say app right here let me just go down and select all these just holding down alt by the way when a double-click to select them all I’m going to delete that and replace each one with the router so what we’re doing
Is creating an instance of this router which is like a mini app it’s like the app but standing alone it doesn’t do anything we have to use the router inside an app so we’re creating this instance of the router we’re attaching these handlers to the router and then at
The bottom I’m going to export this router so to do that I say module dot exports and set that equal to the router ok does that make sense so we’re exporting this now this kind of mini app with all of these different route handlers now what we can do is we can
Import this inside app yes and we can use that inside our app so let me go to the top and now let me say over here we want to say Const blog routes is equal to require and we want to go into the routes folder then we want the blog
Routes file ok now also before we go on this thing right here we don’t need that in this file anymore because we’re not interacting with the blog model in this file directly so let’s cut that from there and instead paste it over here where we are using it up here at the top
Because we using it in these route handlers so let me save this and come back over here now we’re importing these blog routes how do we use them inside our Express app well all we need to do is come down to here where we had the blog routes defined and
We can see app use as we would use a bit of middleware and all we’re gonna do is use the blog routes like so that’s all we need to do and this is going to say okay well I’m going to look at these which are over here and I’m going to
Apply all of these handlers to the app that’s what it does okay so if I save this now everything should still work the same way let me try this out I’m gonna refresh and we should still get this page with all of the blocks but we
Don’t so there seems to be some kind of error let me open up the terminal and we see right here module not found let me scroll up and see what’s going on okay I think it’s because up here we’re requiring inside blog routes the models
But we need to come out of the routes folder first of all so let me double dot that means come out of the current folder then go into models which is right here then I want the blog file so save that hopefully this should work now
Let me first of all go to the home page let’s see if this works yep it does and if we go to Yoshi’s party this should work yes it does all right so these are all working the same way let’s try adding a new blog and this
Is just kind of hanging so let me see what’s going on let me just go to the blog routes and see here right the problem is we have this URL handle right here so forward slash blogs at forward slash create but we also have this one
At the top right here get forward slash blog /id right now when we go to forward slash blog forward slash create who’s to say that that create part shouldn’t be an ID because remember the code runs from top to bottom so what I actually
Need to do is grab this and I need to paste it above this one right here so when the request zyne for /blog forward slash create this one fires first and not this one because if this one fires first then we’re going to try and find a blog with the idea of
Create and that’s not going to work so that’s the reason that’s not working let me save that and let me go back and try this again so new blog and hopefully this should work down and lead us ok so let me add this new blog submit it and see if this works
And voila so everything now still works so then that is the Express router it allows us to extract the routes into a different file create kind of like a mini app and then use those routes in our app when we use app don’t use blog
Routes now if we wanted to we could go one step further and we could scope this to a specific URL so I could say that I want to scope this to for example forward slash blocks now what is this gonna do well it means it’s only gonna
Apply these blog routes when we go to forward slash blogs but check this out if I go to forward slash blogs now then it’s gonna hang and it’s not gonna work but if I go to forward slash blogs forward slash blogs then we should get
The home page so what’s going on well if we go to our blog routes we can see we have forward slash blogs here and also forward slash blogs right here so basically what we’re saying only use these blog routes when the URL begins with forward slash blogs but then on top
Of that we’re saying well after that should come forward slash blogs so if we’re scoping it out right here we no longer need where we say blogs right here and we can just now forward slash because then that would mean we’ve already gone to forward slash blogs and
We’re just adding on the forward slash at the end of it which is the same thing right so we can take away the blog’s bit from each one of these if we wanted to like this and because we scoped it out – forward slash blogs it’s going to
Automatically apply that to the start of each one of these handlers so now we’re scoping it out right here and we don’t have to add that so each one of these handle its and that makes this a little bit more reusable because if we change the URL structure
In the future we don’t have to change everything right here all we’re doing is changing it right here where we scope the routes out so if I save this now everything should still work the same way let me just test this if we click on
This it should go to the home page yep it does and if we go to about we get the about thing that’s got nothing to do with blocks so that doesn’t really matter if we got a new block then we still get this if we try to add a new
One it should still work awesome so this is all working so now we’ve done that let’s try and split up our code a little bit more by taking an MVC approach so a lot of the time you’ll hear developers say they want to take like an MVC approach now what does that even
Mean well MVC stands for Model View controller and it’s a method of structuring our code and our files and it aims to make our code more modular reusable and easier to maintain it’s not essential you use the methodologies of MVC but it can be helpful especially as your projects get larger so we’ve
Already seen the M and the V models and views so views are where we make our HTML templates that a user will see and models are how we describe our data structure and we use them to interact with the database so the last piece of the puzzle is controllers now
Controllers will be the thing that forms the link between our models and our views they’re like the middlemen that use models to get data and then pass that data into a view now we’ve actually already done that directly in our route handlers right but the idea of using
Controllers is that we just extract those handler functions into a separate controller file then we can just reference those controller functions in our routes file again though you don’t have to do this the idea behind this is just to make our code easier to manage and to understand we’re just splitting
Our code into different areas of files and then each area of file has its own job to do so our route file matches incoming requests and it passes those requests to the correct controller function a controller communicates with the appropriate model to get data into a
View and then the view then renders that data into its template and it gets sent to the browser so all we’re basically going to do is extract our route handler functions into a separate controller file to make everything a little easier to read and understand
So then remember the aim of all this is to make our code cleaner and neater so what we’re going to do is extract all of these different handler functions from the routes and we’re going to place those into a separate controller file and then we can just reference those
Control of functions from this routes file so what I’m going to do first of all is create a new folder called controllers and now notice we have muddles views and controllers MVC right and inside here I’m going to create a new file called blog controller jas so all of our functions for this
Resource blocks so all of these functions that we’re using these routes they’re going to live inside this blog control at file now that what I’m gonna do is create functions using a similar kind of naming convention as mdn so that looks something like this I’m going to
Create a function called blog index to get all the blogs and inject those into the index view I’m going to use blog details for the name of the function for this one to get a single blog which is this right here I’m going to use blog
Create get to send back the actual form so this is a get request blog create post to add a new blog and then blog delete to delete a blog so that’s the naming convention I’m going to use for these control up functions so the first thing I want to do is create these
Functions so let me do that Const blog underscore index and that is going to be equal to a function oops let’s spell this correctly I can never do that for some reason index this is equal to a function and inside the function we want to do all of this logic or right here
Right not that one we want all of this one or right here so let’s cut it from there and let’s paste it in here now then first of all we can take in the request and the response object because remember in these functions we get access to that request
And response so I’m going to say request and response and then we also need to import the blog model so let me grab that from here because we’re not going to need that anymore in this file because all of the logic is not going to be in here anymore it’s
Going to be in this one instead so let me paste this at the top so we have it right there so now if I say at the bottom module exports is equal to an object and inside this object we’re going to output the blog index as a
Property right so now we have access to that from anywhere we import this file so let me just save this for a second and we’re going to import it over here so I’m gonna say Const and then blog controller is equal to our require and we want to require dot dot forward slash
To come out of the current folder which is the routes then go into the controllers folder and then we want the blog controller right so now we have access to this and we can access this function on it blog index so now instead of this function firing right here we
Can just say blog controller dots blog index so now all it’s going to do is get this function all right here and it’s going to place it right here so it’s doing exactly the same thing it’s just that now we’ve extracted it from here and we’ve placed it in a controller file
And we’re going to do that now for every single function down here so now let’s do the next one which is blog details so let’s create that function so Const blog underscore details and that’s equal to a function we’re taking the request and the response object and in here we just
Want to paste all of the details so that’s this thing right here so let’s cut that from there and let’s paste it right here instead and then I want to export that as well so blog underscore details like so okay so that’s that one done well let’s go and reference that
Over here as well so I’ll say here that this should be blog controller dots blog details okay now the next one over here is blog creates get so that’s the one for sending back the actual form so when we click on that that’s that request so let’s create this
Function down here Const blog underscore create underscore gets that’s equal to a function request and response goes into that function and inside let’s go and grab this thing right here where we render the create page so let’s cut that from here and paste it inside here I’ve
Noticed a spelling error so let me fix that so we need to export that function as well so blog underscore create underscore gets and we can now use that over here instead of this function so blog controller dot blog underscore create get okay so two more to do let me
Go back and let’s do the next one which is blog creates host so in fact let me just copy this so I’m not typing out the same thing over and over blog creates post and then inside here we’ll delete that and then we’ll export blog create post and we need to get all
Of the details from here where we send a post request which is this thing right here so let me grab that and paste it on right here now we can reference this function over here instead of this so blog controller dots and it’s blog create post and finally we need to do
This one down here so let me go back over it and this function is called blog delete so we’ll say Const blog delete is equal to a function request and response goes into that and then inside we want to get all of this logic right here cut
It from there and paste it all right here and then finally export that which is blog underscore delete like so and then we can come back over here and we can say right here blog controller dots blog underscore delete and that is it awesome so now we’ve extracted all of our different
Handlers into a blog control file or right here so we’re keeping all of the controller logic separate from the routes and that way our routes look a lot neater and we’re kind of modularizing our code a bit more so it’s easier to read and easier to update in
The future so before we get too carried away let’s just make sure this Allston works nothing should change everything should still work the same way because we’ve not changed the functionality of anything so yep the home page works if I go to about that should still work if I
Go to new blog that should still work try to add this submit that still works if we go to a details that works if we delete one this should work but it’s not doing so let’s just go back and see what’s going on over here ok yep my mistake this should be delete
Not details all right so we just had the wrong controller method applied to that so if we go back over here now and try to delete this hopefully this should work if we click on delete yet it works and then redirects was back to the home page awesome so now our code is
Structured in a much more logical way which is easier to maintain and for every new type of resource and set of routes you would follow this pattern you’d have a route file for the routes and model for the data and a controller for the handlers and then a folder for
It to views as well now just speaking of views I think it actually I’d like to structure our views a little better too since at some point we might have multiple different resources right you could have users Paul’s comments categories as well as blogs therefore you might need for example a create a
Details and index for each individual resource right now we couldn’t create multiple of those in here because the names would clash so what we could do is we could scope these by putting them in their own folder so for example I could create new folder called blocks inside views
And then I could place the create in there the details in there and the index in there they’re all the views that relate to blogs right then if I had a different resource in the future I could create a folder for that and do the same
Index details and create in that so what I’m gonna do now just quickly is go to the blog controller and I need to wherever I am rendering a view update that because we’ve put it in a new folder and now it should be blogs forward slash create so it knows to go
Into the blog’s folder first of all and where else do we do this blogs forward slash details and then blogs forward slash index and if we save that and come and refresh everything it should still work the same way but it doesn’t we get an error and that’s because remember
We’re using partials inside these things right here and now they’re in a different location so we need to go back to these three things here and we need to add double dots each one of these so it knows to come out of the blog folder first of all then into partials so let’s
Do that for each one of these so that’s the index let’s do details and add a dot in front of that one in front of that one and I think it’s the top one now yep and then finally let’s do create and do a dot
Here and a dot here and a dot here save that and now if we come over here and refresh hopefully this works yep everything now still works awesome okay there my friends so there we go that is MVC not essential but definitely helpful
-
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
Amazing Job sir – clear and concise course. Thank you for all the hard work put into this course ; appreciate you.
LOL MVC still doesn't make sense to me. You're just shifting all the code from the route file to the controller file 🤷🏾
Thank you so much for this series. How can I host an app like this online? Are there free hosting services?
What a frustrating yet awesome journey! It's already 2023 and still relevant. After 1 week of following the tutorial I was able to learn Mongo DB, the concept of Servers, MVC's, and Mongoose. I am now confident to take these new backend learnings into higher levels. Thank you so much, Net Ninja!
What would a PUT request look like? I've been able to create a route for /blogs/edit/:id and populate the form with the existing blog entry, and change the form method to PUT, but I'm not sure where to go from there and I can't let it go. 😂
Thanks for useful tutorial. This is the best MVC tutorial
all right mr, im done this course
thanks
Thank you. What an amazing course. I had lost the confidence in programming in general, but this course really helped me understand the backend concepts and get better.
I do have one question though: The MVC stuff which was taught here, when I do personal projects, should I implement this while setting up the files, when I feel the project is getting clunky, or when the project is finished? What is the best time?
I love your way of teaching. Would you please make a Crash course on Redux Toolkit please?
thank you Ninja
Where is code?
thank you
This is my first time learning node, back end and MVC. First off, superb course in so many ways (content, to the point, duration, example etc.). I do have one question, I am intrigued how the models are derived from the database schemas. Coming into this, I had this idea in my head that you defined your JavaScript classes somewhere in your models directory and then somehow exported this to the database.
There's a project I've been building in my head as I've been watching this course and that is how I thought one would normally go about it, but it seems it is the other way around (define Schemas in DB first, then from there define your objects/classes for your logic). I don't know if anybody could provide some thoughts about this.
Again, superb course, thank you so much for everything 😀
thank you thank you thank you
I learned so much
what does
app.use((req, res, next) => {
res.locals.path = req.path;
next();
});
mean????
Thank you very much for this tutorial <3
but I have an error :
astError: Cast to ObjectId failed for value " 6320c05429ec4ccbea69dfd6" (type string) at path "_id" for model "Blog"
that's happen when I declare id on delete method – const id = req.params.id
I replace it with – const id = mongoose.Types.ObjectId(req.params.id.trim());
and it worked
can someone explain what happen ?
note : it works when I write – const id = req.params.id on get method but not work in delete method
Thank you for this pretty course
I'm guessing you must be about 167 years old to have such an in-depth understanding of so many aspects of each subject and so many subjects!
Best video I have watched regarding those Topics. You helped me so much Sir!
Best tutor best mvc explanation! thank you for sharing it.
at 7:04 why it goes to `/blog/:id` instead of `/blog/create`? these are completely two separate and different routes! why should it maintain an order? If this is how it works then moving the /create to the top won't cause same issue when one hits /:id url ?
awesome
Thank you for creating this course, really gave me the knowledge I needed to start learning backend programming. Cant wait to really get into it
how can you integrate this in a react project? not sure what to do with the render method
hi, i am getting hard time on controller due to this error " TypeError: Cannot read properties of undefined (reading 'status')" can you help?
18:18 ops, not details controller for the delete rote but blog_delete should been
Such a clear and concise tutorial series. Thank you!
Thank you from Paris – France. Merci !
I'm having problems with ../models/blogs – it still says module not found when I edit it in memberRoutes.js
Shaun <3 <3 <3 You saved me
i have a question:
what does this middleware do:
app.use((req, res, next) => {
res.locals.path = req.path;
next();
});
Awesome tutorial.
Even UDEMY premium courses dont provide these kind of details. Thanks Shaun.
best tutorial on mvc architecture
Awesome tutorial
This has been a very awesome series !! went from zero to creating an entire application within just a few video !!
OMG I never understand MVC before, your explanations is amazing!
Best explanations on those topics, I've found in youtube!
Thank you!
Interesting, I like how you made the controller agnostic/loosely coupled from express. However, it's still tightly coupled to the model and mongo, as model implementation details are happening inside . There could be additional layer of abstraction in the controller to be model/db agnostic.
Great series of video tutorials. Everything was explained precisely. <3
the best tutorials I never regret watching, all your tutorials are always on point, short yet well explained, and well understandable to me, and, thank you
Wow… I’m just running out of words… What a perfect explanation!
wow this guy explains every thing very well
Really cool chapter.
Finally, we have a clear/comprehensible explanation of MVC.
I'm just wondering why we didn't keep a default "index" page, separeted of the blog's one.
Can I get freelance job as a MERN stack developer ?
Great tutorial sir 🧡🧡🧡
Finished this, absolutely amazing explanation. Got your novice to ninja and D3.js courses on udemy. I was a bit slow on those, but after this I just subscribed to your ninja pro plan and I got really pumped up. You are an excellent and passionate teacher I might add. Thans man!