Selected topic
Routing
Prefer practical output? Use related tools below while reading.
Routing is a fundamental concept in Express.js that enables you to handle HTTP requests and map them to specific routes. Here's an overview of basic routing in Express:
GET, POST, PUT, etc.app object (which is an instance of Express) and specify the HTTP method and path:
javascript
const express = require('express');
const app = express();// GET /hello
app.get('/hello', (req, res) => {
res.send('Hello World!');
});
// POST /users
app.post('/users', (req, res) => {
// Handle user creation logic here
});
GET /hello maps to the /hello path and responds with a "Hello World!" message when an HTTP GET request is made.POST /users maps to the /users path and will handle user creation logic.javascript
const express = require('express');
const app = express();// Create route for getting all books
app.get('/books', (req, res) => {
const books = [
{ id: 1, title: 'Book 1' },
{ id: 2, title: 'Book 2' }
];
res.json(books);
});
// Create route for creating a new book
app.post('/books', (req, res) => {
const newBook = req.body;
// Save the new book to the database
console.log(newBook);
res.status(201).send('Book created successfully!');
});
// Start the server
const port = 3000;
app.listen(port, () => {
console.log(Server listening on port ${port});
});
GET /books returns a JSON array of all books.POST /books creates a new book and saves it to the database.javascript
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
// Handle user retrieval logic here
});
In this example:GET /users/123 will pass 123 as the value of userId.