In the vast expanse of the Node.js universe, Express.js is a popular and powerful web application framework that simplifies building web and mobile applications. One of its key features is routing, which helps manage the navigation between different pages of your application.
In simple terms, routing in Express lets you define how a server will respond to various URL requests, allowing you to organize your application and create dynamic content.
Routing is essential because it enables you to:
To begin, make sure you have Node.js and Express.js installed. If you haven't already, follow the Node.js Setup Guide and the Express.js Setup Guide on our website.
Once you have everything set up, create a new folder for your project and navigate into it in your terminal or command prompt:
mkdir express-routing-tutorial
cd express-routing-tutorial
Now, let's initialize a new Node.js project and install Express.js:
npm init -y
npm install express
Create a new file called app.js in your project folder and let's dive into routing!
Open app.js and paste the following code to set up a simple Express server:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});Save the file and run the server by executing node app.js in your terminal or command prompt. Open your browser and navigate to http://localhost:3000. You should see "Hello, World!" displayed on the screen.
In this example, we created a simple route for the root URL (/). When a GET request is made to the server at the root URL, Express responds by sending the message "Hello, World!".
Let's extend our application to display dynamic content based on the URL. Open app.js and replace the existing code with the following:
const express = require('express');
const app = express();
const port = 3000;
app.get('/user/:name', (req, res) => {
const name = req.params.name;
res.send(`Hello, ${name}!`);
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});Save the file and run the server again. Now, if you navigate to http://localhost:3000/user/John in your browser, you should see "Hello, John!".
In this example, we created a new route for the /user/:name URL, where :name is a parameter that captures the value after /user/ in the URL. This allows us to display dynamic content based on the URL.
What does routing in Express.js do?
So far, we've been using the GET method for our routes. However, Express also supports other HTTP methods like POST, PUT, DELETE, and more. Let's create a simple example for handling a POST request:
app.post('/login', (req, res) => {
const username = req.body.username;
const password = req.body.password;
if (username === 'admin' && password === 'password') {
res.send('Login successful!');
} else {
res.send('Invalid username or password.');
}
});In this example, we created a new route for the /login URL. When a POST request is made to the server with the username and password, the server will check if the credentials are valid and respond accordingly.
Congratulations! You've taken your first steps into the world of routing in Express.js. With this knowledge, you're well on your way to building dynamic and interactive web applications. Keep exploring, experimenting, and learning!
Remember to check out our other guides for more in-depth tutorials and resources on Node.js and Express.js. Happy coding! 🚀