Node.js Basic Routing

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.

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.

0 Interaction
989 Views
Views
13 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home