express path params code example

Example 1: express get url parameters

app.get('/path/:name', function(req, res) {
  res.send("tagId is set to " + req.params.name);
});

Example 2: express param in url

app.get('/p/:tagId', function(req, res) {
  res.send("tagId is set to " + req.params.tagId);
});

// GET /p/5
// tagId is set to 5

Example 3: 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 4: express router file

var express = require('express');
var router = express.Router();

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// define the home page route
router.get('/', function (req, res) {
  res.send('Birds home page');
});
// define the about route
router.get('/about', function (req, res) {
  res.send('About birds');
});

module.exports = router;

Example 5: express route parameters

app.get('/users/:userId/books/:bookId', function (req, res) {
  res.send(req.params)
})

Example 6: express route parameters

var express = require('express');
var http = require('http');
var app = express();