express js routing parameters code example
Example 1: define a route with path paramters in nodejs
var users = {
'azat': {
email: '[email protected]',
website: ' http://azat.co ',
blog: ' http://webapplog.com '
}
};
var findUserByUsername = function (username, callback) {
// Perform database query that calls callback when it's done
// This is our fake database
if (!users[username])
return callback(new Error(
'No user matching '
+ username
)
);
return callback(null, users[username]);
};
app.get('/v1/users/:username', function(request, response, next) {
var username = request.params.username;
findUserByUsername(username, function(error, user) {
if (error) return next(error);
return response.render('user', user);
});
});
app.get('/v1/admin/:username', function(request, response, next) {
var username = request.params.username;
findUserByUsername(username, function(error, user) {
if (error) return next(error);
return response.render('admin', user);
});
});
Example 2: express route parameters
app.get('/users/:userId/books/:bookId', function (req, res) {
res.send(req.params)
})
Example 3: express route parameters
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
Example 4: route parameter in node
var express = require('express');
var fs = require('fs');
var app= express();
app.get('/index/profile/:id',function(req,res){
// res.send('profile with id' + req.params.id)
});
app.listen(3000,'127.0.0.1');
console.log('lsitng');
Example 5: express route parameters
app.get('/',function(req,res)
{
res.send("Route path at base address");
});