Branch behavior by request path
Route-aware middleware
Express.js · Pipe
req.path is a string containing the path portion of an Express request URL. It excludes the query string, and mounted middleware sees the path without its mount point.
req.path is a string property on the request object that reports the path portion of the incoming URL. It excludes the query string, and middleware mounted at a path sees the path after that mount point rather than the mount point itself.
req.pathString containing the path part of the request URL.
req.path exposes the URL's path portion as a string.example.com/users?sort=desc, the path portion is /users.console.dir(req.path).req.path may differ from the original URL path.const express = require('express');
const app = express();
app.get('/users', (req, res) => {
res.json({ path: req.path });
});
app.listen(3000);Run the app and request /users?sort=desc; the response contains /users, without the query string.
Route-aware middleware
Request logging
Path-based metrics
req.path contain?It is a string containing the path part of the request URL. For /users?sort=desc, its value is /users.
Follow-up: How would you obtain the query string values? Use the request's query-related API, such as req.query, rather than req.path.
req.path include query parameters?The query string is not part of req.path; only the URL path is represented. Therefore /users?sort=desc produces /users.
Follow-up: What happens in mounted middleware? The mount point is omitted from the value visible there.
req.path in middleware?It is affected by middleware mounting: the mount point is not included when the property is read from that middleware. This reflects the path remaining after the middleware's mount location.
Follow-up: Why should middleware account for this? Path checks inside mounted middleware must use the shortened path rather than the application's original full path.
req.urlreq.originalUrlreq.baseUrlreq.queryreq.params