MERN Stack Tutorial #3 - Express Router & API Routes

Net Ninja · Beginner ·🔧 Backend Engineering ·4y ago

Key Takeaways

The video demonstrates setting up API endpoints using Express Router in a MERN Stack application, defining routes for GET, POST, and DELETE requests, and working with a database using Mongoose.

Full Transcript

all right then gang so in this lesson we're going to focus on setting up the different routes or api endpoints for our express api and what we want to eventually do is interact with the database using this api to do things like get workouts from the database and send them back to the clients or add new workouts or delete them or update them etc so we're going to set up various endpoints to do this and i just wanted to run through these first of all in a slide so we're going to have a get request handler to forward slash workouts and this handler would get all of the workout documents from the database and send them all back in json format to the browser the post request to forward slash workouts that handler would create a new workout document in the database then we'd have a get request handler to forward slash workouts forward slash sum id where this id is a route parameter and would represent the id of a particular workout and that would get us a single workout document from the database and send it back to the browser so this would be the workout we get with this id and then we have a delete request to forward slash workouts forward slash id again where this is the id of the document that we want to delete and that would delete a single workout from the database and finally a patch request which would be used to update certain fields inside a workout and that would be to forward slash workouts forward slash id again where this is the id of the workout that we want to update okay so they're the different routes that we need to set up in our application all right so we want to set up all of these different routes and route handler functions where do we do that in our code well we could do it inside the server.js file like we did with this right here but what i want to do is not bloat out this particular file and keep this quite clean and instead what i'd like to do is create a different file to keep all of our routes in so what i'm going to do inside the back end folder is create a new folder first of all called routes and then inside here creates a new file called workouts and all of our different workout routes are going to go inside this file now the way we created a route over here is by using this app right here and then saying dot gets and if we wanted a post request handle out we would say app dot post and if we wanted a delete request handler app.delete and so forth but we don't have access to the app inside this file right here so how do we create those routes well the way that we do it is by using the express router so first of all we need to require express up here at the top of the file so we say const express equals require the express package and then below that we can say const router and we set that equal to the express dot router with the capital r and invoke that and that creates an instance of the router for us and then we would attach a handler to dot this so example and then that could be to just forward slash and we'd have some kind of function that fires when that request comes in and then at the end of the file once we've created all of our routes we can export the router and the way we do that is by saying module that exports is equal to the router like so so we'd set up all of these different routes so we might have four or five of them right here on this express router and then we export the router at the end then what we could do inside the server.js file is require that particular router right here that we export with all of these different routes attached to it so let's do that i could say const workouts routes and you can call this what you want it doesn't really matter i'm going to name it workout routes since that's what they are and we set it equal to require and then we want to go into the routes folder so dot forward slash into the routes folder and then forward slash workouts we don't need to put the extension it figures that out so we have to work out routes and then all we need to do is use those routes on our app and the way we do that is come down here i'm going to get rid of this one because we don't need this route anymore that was just to test the api so instead i can say app dot use this time and we're going to use the workout routes so we grab them and we paste them in here and basically what that does is it grabs all of the different routes that we attach to the router right here and it basically uses them on the app so if we have a get handler right here it would be the same as saying app.get right here and then whatever the url is or the path and then the function okay so it just attaches all of those routes to the app now what i want to do as well is i want to only fire these routes when we come to a specific path so for example i could place in another argument right here before workout routes to specify a path and that's going to be forward slash api forward slash workouts so what that means is when we fire a request to this route right here then i want you to use these routes and they become relative now so if this is just forward slash it would mean when a user goes to forward slash api forward slash workouts forward slash then we fire this function now down here if i was to do another one let me just copy that and paste it right here to say hello or something like that then this would fire this function when we went to forward slash api forward slash workouts forward slash hello does that make sense okay so we have that set up right here now that's all we need to do so now we can go ahead and start creating these different routes so we have this one for just forward slash and this is going to be to get all of the workouts because remember we're going to go to forward slash api forward slash workouts and that should give us all of the workouts this one right here so what i'm going to do for now is just taking the response or the request rather and the response object and then inside here i'm going to say response.json to send some json back and the json is just going to have a message on it to say get all workouts so this is just a dummy response for now so that when we're sending requests from postman we can see a response all right so let me do a comment above that to say this is to get all workouts all right and then let's come down here now we need one to get a single workout cannot spell single all right so let's say now router.get and this is going to be to forward slash and then colon id this colon represents a route parameter whereby this can change and then we fire a function we get the response and the request object like so and inside here we'll send a response so response.json and i'm gonna add a message property to this to say get single workout all right so i'm going to show you how we can access this route parameter later on for now we're just sending this simple response back the next one we want to do is post a new workout so post a new workout to create one so we say this time router.post so we're handling a post request this time not a get request and this is going to be to just forward slash because again we have this stuff in front of it so when we send a post request to this it's going to fire this function in a second so request and response and then inside here for now we'll just send a json response so response.json and we'll have the message property which will say post a new workout and you know what i'm going to do i'm going to just copy this now a couple of times and paste it down here so the next one is going to be to delete a workout and right here we need to change this to a delete request instead of post so delete and this needs to go to forward slash colon id where this is the id of the thing that we want to delete and then right here we can say delete a workout like so and then the last one is to update a workout so let's say update a workout like so this needs to be a patch request to update something and that's going to be to forward slash colon id as well and then right here we say update a workout like so and that's pretty much done they're all the routes that we need for now so we're creating the router then we're adding all of these different request handlers onto that router and we export the router at the end then we use that router right here for this particular path so if we just go to forward slash then it's not going to fire this thing right here because it doesn't have this in front of it it's only when we go to this route right here these routes are added on to the end of it okay cool so that's pretty much done i think and yeah okay there's one more thing i think we should do so you know when you're handling a post request like this or even a patch request where we're sending data to the server because if we want to add a new workout to the database we have to send the data for that workout document we can access that from the request object right but we can only access that if we use a bit of middleware in an express app and that middleware is express.json so what i'm going to do is come above this middleware and say app.use and it's built into express so we can just say express dot json like so and what that does is any request that comes in it looks if it has some body to the request so some data that we're sending to the server and if it does then it passes it and attaches it to the request object so that we can access it in the request handler so if i save this now i could if i wanted to get access to the request body by saying request dot body now in a post request all right now i'm not going to do that for now but we will need that later on so i just thought i'd add in this middleware to prepare us for that but now we have all of these different routes i'm going to open up the terminal to make sure everything's still running it is we're going to try these routes out now in postman but before we do that i've just noticed an error right here these are the wrong way around it should be request first and then response all right so now let's try this out all right then so in postman i'm inside the moon app folder we've got open this request that we created earlier now i'm going to change this back to get and this time if it goes to just localhost port 4000 forward slash if we click send then we get an error back because now the end point is not just forward slash it should be forward slash api forward slash workouts like so and if we send a get request to this then we should get a response which we do so i'm going to save that now okay so now that's done and in fact let's edit this i'm going to say this should be api forward slash workouts as well all right so now that's saved let's create the next one so we'll do now a get request to a specific um document so that needs to be to the same end point so let's paste that in here but also now with some kind of id on the end so if we send this now then we should see get a single workout back which we do cool so now i'm going to save this one as well inside the mirn app folder save that so we can use it later okay let's cross those off the next one i want to do is a post request and this is going to be to the same end point and normally we would add a request body because we want to create a new workout in the database and we need to send that data to the server to do that but we're not going to do that just yet i just want to make sure that the endpoint works so let's send this and see yep post a new workout that works i'm going to save this for later inside the mern app folder all right let's cross that off next let's do the delete request so select deletes paste this in and there should be an id on the end of this as well send it and yeah we get this back which is correct so let's save this like so inside the main app folder and then finally we want to create a patch request so let's select patch paste in this endpoint and add some kind of id send that and we can see update a workout comes back awesome so these are all working and now we have these different requests saved so we can test them out later on when we're actually working with data next up we're going to create a database and we're going to also talk about mongoose which is a package we can install into our application to help us work with the database as well

Original Description

Hey gang, in this MERN tutorial we'll create all of the workout routes we need for the api and test them out using POSTMAN. ⭐⭐ Get the full course now (without ads) on the Net Ninja Pro site: https://netninja.dev/p/mern-stack-tutorial ⭐⭐ Get access to all free & PREMIUM courses on Net Ninja Pro: https://net-ninja-pro.teachable.com/p/net-ninja-pro/ 🥷 Course Files (GitHub): https://github.com/iamshaunjp/MERN-Stack-Tutorial 💻 Node.js & Express Crash Course: On Net Ninja Pro - https://netninja.dev/p/node-js-crash-course On YouTube - https://www.youtube.com/watch?v=zb3Qk8SG5Ms&list=PL4cUxeGkcC9jsz4LDYc6kv3ymONOKxwBU 💻 MongoDB Crash Course: On Net Ninja Pro - https://netninja.dev/p/complete-mongodb-tutorial On YouTube - https://www.youtube.com/watch?v=ExcRbA7fy_A&list=PL4cUxeGkcC9h77dJ-QJlwGlZlTd4ecZOA 💻 React Full Courses: On Net Ninja Pro - https://netninja.dev/p/build-websites-with-react-firebase On Udemy - https://www.thenetninja.co.uk/udemy/react-and-firebase On YouTube - https://www.youtube.com/watch?v=j942wKiXFu8&list=PL4cUxeGkcC9gZD-Tvwfod2gaISzfRiP9d 🔥🔥🔥 Other resources: React Context & Hooks tutorial (on YouTube) - https://www.youtube.com/watch?v=6RhOzQciVwI&list=PL4cUxeGkcC9hNokByJilPg5g9m2APUePI VS Code - https://code.visualstudio.com/ MongoDB Atlas -https://www.mongodb.com/atlas/database POSTMAN - https://www.postman.com/downloads/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Net Ninja · Net Ninja · 0 of 60

← Previous Next →
1 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

This video teaches how to set up API endpoints using Express Router in a MERN Stack application and work with a database using Mongoose. It covers defining routes for GET, POST, and DELETE requests and using route parameters to specify a path.

Key Takeaways
  1. Create a new file to keep all routes in using Express Router
  2. Use Express Router to create routes in a separate file and export it
  3. Require the router in the server.js file and attach it to the Express app
  4. Attach routes to the app using app.use()
  5. Define routes for GET, POST, and DELETE requests
  6. Use route parameters to specify a path
  7. Send JSON responses using response.json()
  8. Install Mongoose to work with the database
💡 Using Express Router to separate routes from the main application code makes it easier to manage and maintain the application.

Related Reads

📰
The Object in Your Field Is Not the Object You Wrote
Understand how @Transactional works and why it may silently fail due to proxy classes, and learn how to troubleshoot and resolve these issues
Medium · Programming
📰
I built an offline CLI that audits a legacy PHP app in one command — and shows you the fix
Learn how to build an offline CLI tool to audit legacy PHP apps and get fixes with one command
Dev.to · getobserver
📰
Web Developer Travis McCracken on The Simplicity of Net/HTTP in Go
Learn how to leverage Net/HTTP in Go for simple backend development from web developer Travis McCracken
Dev.to · Travis McCracken Web Developer
📰
Laravel Policies Explained: Protect Your Application the Right Way
Learn how to protect your Laravel application with policies, controlling user actions and permissions
Medium · Programming
Up next
Indian Express Editorial Analysis by Chandan Sharma - 1 JULY 2026 | UPSC Current Affairs 2026
StudyIQ IAS
Watch →