Shoulder.dev Logo Shoulder.dev

Routing - benhall/express-demo

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/):

  1. Implicit route definition in app.js: In this approach, routes are defined directly in the main app.js file using the app.get(), app.post(), app.put(), and app.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.

  1. 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, in users.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 server
  • POST: Sends data to the server for creation or modification
  • PUT: Updates existing data on the server
  • DELETE: Deletes data from the server

For more information on routing in Express.js, see the following resources: