express basic routing syntax
Express Basic Routing Syntax
To define routes in Express, you can use the app.METHOD(PATH, HANDLER)
syntax, where:
- app
is an instance of the Express application.
- METHOD
is an HTTP request method, such as GET, POST, PUT, DELETE, etc.
- PATH
is the path or URL pattern for the route.
- HANDLER
is a callback function that gets executed when the route is matched.
Here is an example of the basic routing syntax in Express:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.post('/users', (req, res) => {
res.send('Creating a new user...');
});
app.put('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`Updating user with ID ${userId}`);
});
app.delete('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`Deleting user with ID ${userId}`);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example:
- The app.get('/', ...)
route handles GET requests to the root path (/
) and sends the response 'Hello, World!'
.
- The app.post('/users', ...)
route handles POST requests to the /users
path and sends the response 'Creating a new user...'
.
- The app.put('/users/:id', ...)
route handles PUT requests to the /users/:id
path, where :id
is a route parameter that can be accessed using req.params.id
. It sends a response with the user ID extracted from the route parameter.
- The app.delete('/users/:id', ...)
route handles DELETE requests to the /users/:id
path, similar to the PUT route.
The app.listen(3000, ...)
line starts the Express server and listens on port 3000 for incoming requests.
Please note that this is just a basic example, and there are many more features and options available in Express for routing and handling requests.