Routing in the context of a web application refers to the process of determining how an application responds to a client request to a particular endpoint, which is a specific URL or route. In the Express.js framework, routing is handled by defining routes and associating them with specific handler functions.
There are several ways to define routes in an Express.js application. Here are some examples using the code from the provided GitHub repository (https://github.com/benhall/express-demo/):
- Implicit route definition in
app.js
: In this approach, routes are defined directly in the mainapp.js
file using theapp.get()
,app.post()
,app.put()
, andapp.delete()
methods. For example:
app.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
This defines a route for the root URL (“/”) that is handled by the anonymous function.
- Explicit route definition in separate files: In this approach, routes are defined in separate files and then imported into the main
app.js
file. For example, inusers.js
:
var router = express.Router();
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
This defines a route for the URL “/users” that is handled by the anonymous function. The router
object is then exported and imported into app.js
:
var usersRouter = require('./routes/users');
app.use('/users', usersRouter);
The app.use()
method is used to associate the usersRouter
object with the URL path “/users”.
There are also several HTTP request methods that can be used in conjunction with routes, including:
GET
: Retrieves data from the serverPOST
: Sends data to the server for creation or modificationPUT
: Updates existing data on the serverDELETE
: Deletes data from the server
For more information on routing in Express.js, see the following resources: