NodeJS Express Routes
In this tutorial, we'll explore how to handle different types of HTTP requests using Express.js routes. We'll cover the GET, POST, PUT, and DELETE methods and also learn about the express.urlencoded middleware for parsing form data. So, let's dive right in!
Setting Up the Project
Before we dive into the routes, let's set up a new Express.js project. Follow these steps to get started:
Step 1:
Create a new directory for your project and navigate to it in your terminal.
Step 2:
Initialize a new Node.js project by running the following command:
This will generate a package.json file for your project.
Step 3:
Install the Express.js package by running the following command:
Now that we have Express.js installed, let's move on to handling different types of requests.
Creating Express Routes
To handle different types of requests, we need to define routes in our Express application. Let's start with the basic setup.
Step 1:
Create a new JavaScript file, e.g., app.js, and require the necessary modules at the top of the file:
Step 2:
Add the express.urlencoded middleware to parse URL-encoded form data:
This middleware will allow us to access form data submitted via POST requests.
Now, let's define our routes!
GET Route
To handle a GET request, we can use the app.get()
method. Let's create a simple route that returns a JSON response.
In this example, when a GET request is made to /api/users, we send back a JSON response containing an array of user objects.
POST Route
To handle a POST request, we can use the app.post()
method. Let's create a route that accepts form data and adds a new user to our user list.
In this example, when a POST request is made to /api/users, we retrieve the name field from the request body and process the form data accordingly. We then send a simple success message as the response.
PUT Route
To handle a PUT request, we can use the app.put()
method. Let's create a route that updates an existing user's name.
In this example, when a PUT request is made to /api/users/:id, we retrieve the id parameter from the request URL and the new name value from the request body. We then update the user's name accordingly and send a success message as the response.
DELETE Route
To handle a DELETE request, we can use the app.delete()
method. Let's create a route that deletes a user from our user list.
In this example, when a DELETE request is made to /api/users/:id, we retrieve the id parameter from the request URL. We then delete the user with the corresponding ID from our user list and send a success message as the response.
Thatβs it! You've learned how to handle different types of requests using Express.js routes.