Tuesday 5 March 2019

Express: req.originalUrl: Return original request url


req.originalUrl
This property returns original request url.

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

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

appAdmin.get('/users/info', (req, res) => {
 var result = `Base url for appAdmin is ${req.baseUrl}, original url is : ${req.originalUrl}`
 console.log(result)
 res.send(result)
})

appUser.get('/info', (req, res) => {
 var result = `Base url for appUser is ${req.baseUrl}, original url is : ${req.originalUrl}`
 console.log(result)
 res.send(result)
})

// 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 ‘http://localhost:3000/admin/users/info’ in browser, you can see below message.


You can see below message in console.
Base url for appAdmin is /admin, original url is : /admin/users/info

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




You can see below message in console.
Base url for appUser is /user, original url is : /user/info


Previous                                                 Next                                                 Home

No comments:

Post a Comment