You define a route in two parts. First is the HTTP request method (typically GET
or POST
). The second part of the route definition is the path specified in the URL—for example, /
for the root of a website, /login
for a login page, and /cart
to display a shopping cart. These methods often need to be handled completely differently.
The express
module provides a series of functions that allow you to implement routes for the Express server. These functions all use the following syntax:
app.<method>(path, [callback . . .], callback)
The <method>
portion of the syntax refers to the HTTP request method, such as GET
or POST
. For example:
app.get(path, [middleware, ...], callback)
app.post(path, [middleware, ...], callback)
path
refers to the path portion of the URL that you want to be handled by the callback function. The middleware
parameters are middleware functions that are applied before the callback function executes. The callback
parameter is the request handler that should handle the request and send the response back to the client. The callback
parameter should accept a Request
object as the first parameter and a Response
object as the second.
For example, the following examples implement some basic GET
and POST
routes:
app.get('/', function(req, res){
res.send("Server Root");
});
app.get('/login', function(req, res){
res.send("Login Page");
});
app.post('/save', function(req, res){
res.send("Save Page");
});
When the Express server receives an HTTP request, it looks for a route that has been defined for the appropriate HTTP method and path. If one is found, a Request
and Response
object is created to manage the request and passed into the callback function(s) for the route.
Express also provides the app.all()
method, which works exactly the same as the app.post()
and app.get()
methods. The only difference is that the callback function for app.all()
is called on every request for the specified path, regardless of HTTP method. Also, the app.all()
method can accept the *
character as a wildcard in the path. This is a great feature for implementing request logging or other special functionality to handle requests. For example:
app.all('*', function(req, res){
// global handler for all paths
});
app.all('/user/*', function(req, res){
// global handler for /user path
});