Tuesday, 5 March 2019

Express: req.path: return the path part of the url


req.path
Return the path part of the url.

For exmaple
http://sample.com/users/info?sort=desc

req.path has the value "/users/info"

Note
When called from a middleware, the mount point is not included in req.path.

index.js
//Load express module
const express = require('express')

//Put new Express application inside app variable
const app = express()
const appAdmin = express()
const appUser = express()

app.use('/admin', appAdmin)
app.use('/user', appUser)

const port = 3000

function getInfo(req){
 var result = `BaseUrl: ${req.baseUrl}<br />
 originalUrl : ${req.originalUrl}<br />
 path : ${req.path}`
 
 return result
}

//When user hits the home page, then the message prints in browser.
app.get('/', (req, res) => res.send(getInfo(req)))

app.get('/application/help/devGuide', (req, res) => {
 res.send(getInfo(req))
})

appAdmin.get('/users/info', (req, res) => {
 res.send(getInfo(req))
})

appUser.get('/info', (req, res) => {
 res.send(getInfo(req))
})


// Start the express application on port 8080 and print server start message to console.
app.listen(port, () => console.log(`Application started listening on port ${port}!`));

Run index.js.


Open the url ‘localhost:3000´in browser, you can see below message.



Open the url ‘http://localhost:3000/application/help/devGuide’, you can see below message.


Open the url ‘http:// localhost:3000/admin/users/info’, you can see below message.




Open the url ‘http://localhost:3000/user/info’, you can see below message.




Previous                                                 Next                                                 Home

No comments:

Post a Comment