Route parameters are parameters whose values are set
dynamically on a page url.
For example, the url can be like
/users/:userId/movieTickets/:bookingId
When you call the above url like below.
/users/krishna123/movieTickets/booking789
Then userId is mapped to the value krishna123 and
bookingId is mapped to the value booking 789.
Captured alues from the routing object are mapped to
'req.params' object. Let’s see it by an example.
index.js
var express = require('express') var app = express() app.get('/users/:userId/movieTickets/:bookingId', function (req, res) { res.send(req.params); }); var listener = app.listen(3000, () => {console.log('Application started on port ' + listener.address().port);});
Run index.js, and open the url ‘http://localhost:3000/users/krishna123/movieTickets/booking789’
in browser, you can see below kind of response.
You can access the route parameters using ‘.’ Notation.
index.js
var express = require('express') var app = express() app.get('/users/:userId/movieTickets/:bookingId', function (req, res) { var userId = req.params.userId var bookingId = req.params.bookingId var result = `User ${userId}'s booking id is ${bookingId}` res.send(result); }); var listener = app.listen(3000, () => {console.log('Application started on port ' + listener.address().port);});
Run index.js and open the url ‘http://localhost:3000/users/krishna123/movieTickets/booking789’
in browser. You can see below message.
No comments:
Post a Comment