Routing in Node.js allows you to handle incoming requests to specific URLs and define the responses. This tutorial will cover basic routing using Node.js's built-in HTTP module and the popular Express framework.
Node.js Basic Routing
1. Setting Up a Basic Node.js Server
To get started with basic routing, first create a simple HTTP server using Node.js:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World');
});
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
This code creates a basic server that listens on port 3000 and responds with "Hello World" to any request.
2. Routing with Express
Express simplifies routing and server management in Node.js. To get started with Express, install it using npm:
npm install express
Once Express is installed, you can set up basic routing:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
This code creates an Express server that responds with "Hello World" to requests at the root URL ("/").
3. Handling Multiple Routes
You can handle different routes by specifying different paths in Express:
app.get('/about', (req, res) => {
res.send('About Us');
});
app.get('/contact', (req, res) => {
res.send('Contact Us');
});
Now, the server will respond with "About Us" when accessing the "/about" route and "Contact Us" when accessing the "/contact" route.
4. Route Parameters
You can also handle dynamic routes by using route parameters. Here's an example:
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID is ${userId}`);
});
This route will match URLs like "/user/123" and extract the "id" parameter, responding with the user's ID.
5. Conclusion
Routing is a crucial part of any web application. With Node.js and Express, you can quickly set up a server and handle various routes, making it easy to manage different URLs and actions.
Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.