Express

Node.js Express Routing

Express Routing

Node.js Express routing defines endpoints with get and post methods.

Introduction to Express Routing

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. One of its core functionalities is routing, which refers to how an application’s endpoints (URIs) respond to client requests.

In this guide, we'll explore how to define routes in Express using the GET and POST methods, which are commonly used for fetching and submitting data, respectively.

Setting Up an Express Application

Before we dive into routing, let's set up a basic Express application. First, ensure you have Node.js and npm installed on your machine. Then, create a new directory for your project and initialize it:

Next, create an entry file, typically named app.js, and set up a basic Express server:

Defining GET Routes

The GET method is used to retrieve data from a server at the specified resource. In Express, you can define a GET route using the app.get() method. Here’s an example of setting up a basic GET route:

In this example, when a user accesses the root URL (e.g., http://localhost:3000/), the server responds with "Hello, World!".

Defining POST Routes

The POST method is used to send data to the server to create or update a resource. In Express, you can define a POST route using the app.post() method. Here’s an example:

In this example, when a POST request is made to /submit with a JSON body, the server responds with a confirmation message displaying the received data.

Route Parameters

Express allows you to define route parameters to capture values specified at certain positions in the URL. These parameters can be accessed using the req.params object. Here's an example:

In this route, :id is a route parameter. When a request is made to /user/123, the server responds with "User ID: 123".

Handling 404 Errors

To handle 404 errors (resource not found), you can add a middleware function that matches all routes not previously defined:

This middleware will catch any request that doesn't match a defined route and respond with a 404 status and message.

Conclusion

Express routing is a powerful feature that allows you to define how your application responds to client requests. By understanding and utilizing GET and POST methods, you can effectively handle different types of HTTP requests and build robust applications.

In the next post, we'll delve into Express middleware, which allows you to execute code, modify request and response objects, end requests, and call the next middleware function in the stack.

Previous
Express