Wednesday, 6 March 2019

Express: req.params: Get route parameters


req.params
This property is used to access request parameters.

Example
app.get('/users/:userId/info/', (req,res) => {
         res.send(`Sending user information for ${req.params.userId}`)
})

In the above example ‘req.params.userId’ access the route parameter userId.

index.js
const express = require('express')
var cookieParser = require('cookie-parser')

const app = express()

app.use(cookieParser()); 

app.get('/', (req, res) => res.send("Hello World"))

app.get('/users/:userId/info/', (req,res) => {
 res.send(`Sending user information for ${req.params.userId}`)
})

const port = 3000
app.listen(port, () => console.log(`Application started listening on port ${port}!`));


Run index.js and open the url ‘http://localhost:3000/users/krishna/info’ in browser, you will see below kind of response.



Previous                                                 Next                                                 Home

No comments:

Post a Comment