express req params code example
Example 1: express js params
app.get('/path/:name', function(req, res) { // url: /path/test
console.log(req.params.name); // result: test
});
// OR
app.get('/path', function(req, res) { // url: /path?name='test'
console.log(req.query['name']); // result: test
});
Example 2: express get params after ?
GET /something?color1=red&color2=blue
app.get('/something', (req, res) => {
req.query.color1 === 'red' // true
req.query.color2 === 'blue' // true
})
Example 3: express get url parameters
app.get('/path/:name', function(req, res) {
res.send("tagId is set to " + req.params.name);
});
Example 4: express request path
// GET 'http://www.example.com/admin/new?a=b'
app.get('/admin', (req, res, next) => {
req.originalUrl; // '/admin/new?a=b' (full path with query string)
req.baseUrl; // '/admin'
req.path; // '/new'
req.baseUrl + req.path; // '/admin/new' (full path without query string)
});
Example 5: express redirect
res.redirect('/foo/bar')
res.redirect('http://example.com')
res.redirect(301, 'http://example.com')
res.redirect('../login')
Example 6: expressjs query params
// GET /search?q=tobi+ferret
console.dir(req.query.q)
// => 'tobi ferret'
// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
console.dir(req.query.order)
// => 'desc'
console.dir(req.query.shoe.color)
// => 'blue'
console.dir(req.query.shoe.type)
// => 'converse'
// GET /shoes?color[]=blue&color[]=black&color[]=red
console.dir(req.query.color)
// => ['blue', 'black', 'red']