ExpressJS req.{url,originalUrl,path,baseUrl}
These terms sometimes confuse me with their purposes/values.
This post will make everything clear with examples.
All of their definitions can be found in official API docs.
req.url
is not a native Express property, it is inherited from Node’s http module.
Thereq.baseUrl
property is similar to the mountpath property of theapp
object, exceptapp.mountpath
returns the matched path pattern(s).
req.path
: Contains the path part of the request URL.
req.originalUrl
: This property is much likereq.url
; however, it retains the original request URL, allowing you to rewritereq.url
freely for internal routing purposes. For example, the “mounting” feature of app.use() will rewritereq.url
to strip the mount point.
Assume there are two applications: a parent app app
, and a child app admin
import express from 'express'
const app = express()
const admin = express()
app.use('/admin', admin)
admin.get('/login', (req, res, next) => {
console.log(req.url, req.originalUrl, req.baseUrl, req.path)
res.status(200).send('login page')
})
app.get('/login', (req, res, next) => {
console.log(req.url, req.originalUrl, req.baseUrl, req.path)
res.status(200).send('login page')
})
app.listen(3000, () => console.log('listening'))
This is the evaluation result
Request | url | originalUrl | baseUrl | path |
---|---|---|---|---|
/login?pwd=123 | /login?pwd=123 | /login?pwd=123 | /login | |
/admin/login?pwd=123 | /login?pwd=123 | /admin/login?pwd=123 | /admin | /login |
There is also a similar property named app.mountpath.