express routing tutorial code example
Example 1: 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 2: express get all routes and methods
function print (path, layer) {
if (layer.route) {
layer.route.stack.forEach(print.bind(null, path.concat(split(layer.route.path))))
} else if (layer.name === 'router' && layer.handle.stack) {
layer.handle.stack.forEach(print.bind(null, path.concat(split(layer.regexp))))
} else if (layer.method) {
console.log('%s /%s',
layer.method.toUpperCase(),
path.concat(split(layer.regexp)).filter(Boolean).join('/'))
}
}
function split (thing) {
if (typeof thing === 'string') {
return thing.split('/')
} else if (thing.fast_slash) {
return ''
} else {
var match = thing.toString()
.replace('\\/?', '')
.replace('(?=\\/|$)', '$')
.match(/^\/\^((?:\\[.*+?^${}()|[\]\\\/]|[^.*+?^${}()|[\]\\\/])*)\$\//)
return match
? match[1].replace(/\\(.)/g, '$1').split('/')
: '<complex:' + thing.toString() + '>'
}
}
app._router.stack.forEach(print.bind(null, []))
Example 3: 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 4: Basic Routing Express.js
app.get('/', function (req, res) {
res.send('Hello World!')
})
Example 5: express route parameters
app.get('/',function(req,res)
{
res.send("Route path at base address");
});
Example 6: nodejs express routing
// You need to install the following packages
npm install --save mysql express
// And if you don't want to restart your server after every little change
npm install -g nodemon