Creating and managing routes is a fundamental aspect of any web application, and Express.js provides a robust and flexible way of creating them.
Firstly, let’s initialize an Express application:
```
const express = require(‘express’);
const app = express();
```
Creating routes is done via HTTP methods provided by the Express `app` object. Here are some examples:
- Defining a GET route: \`\`\`javascript app.get(‘/example-route’, (req, res) => { res.send(‘Hello World!’); }); \`\`\`
- Defining a POST route: \`\`\`javascript app.post(‘/example-post-route’, (req, res) => { res.send(‘Post request received’); }); \`\`\`
- Defining a PUT route: \`\`\`javascript app.put(‘/example-put-route’, (req, res) => { res.send(‘Put request received’); }); \`\`\`
- Defining a DELETE route: \`\`\`javascript app.delete(‘/example-delete-route’, (req, res) => { res.send(‘Delete request received’); }); \`\`\`
To manage routes, i.e., to keep your code organized, especially for larger applications, Express.js provides the `express.Router` class.
Consider the following example:
```
//Require necessary dependencies
const express = require(‘express’);
//Create a new router object
const router = express.Router();
//Define routes
router.get(‘/example-route’, (req, res) => {
res.send(‘Hello from router!’);
});
//Export the router
module.exports = router;
```
This will create a separate router object, and you can define all the routes inside it. You can import this object in your main server file and use it as middleware:
```
//Import dependencies
const express = require(‘express’);
const exampleRoutes = require(‘./exampleRoutes.js’);
//Initialize app
const app = express();
//Use router as middleware
app.use(‘/api’, exampleRoutes);
app.listen(3000, () => {
console.log(‘Server running on port 3000’);
});
```
The ‘/api’ path here is used as a prefix for all of the paths defined inside your router. This is a good practice to distinguish between different parts (administrative interface, API, user interface, etc.) of your application.