Route Parameter and query string in express (Nodejs)

Route Parameter and query string in express (Nodejs).

 import express from 'express';

const app = express();
const port = process.env.PORT || '3000'

// : it is use for showing dynamic values .
app.get('/delete/student/:id',(req,res)=>{
    console.log(req.params);
    res.send(`Student Deleted ${req.params.id} successfully.`);
})

app.get('/product/:category/:id',(req,res)=>{
    console.log(req.params);
     res.send(`Product Category is ${req.params.category} and id is ${req.params.id}`);
    // desturcture
    // const {id , category } = req.params
    // res.send(`Product Category is ${category} and id is a ${id}`);
});

app.get('/product/mobile/:year/and/:month',(req,res)=>{
    const {year,month} = req.params
    res.send(`Product Year is ${year} and months is ${month} `);
});

app.get('/train/:from-:to',(req,res)=>{
   const { from , to} = req.params
    res.send(`I am form ${from} to ${to} ok.`);
});


app.get('/location/:first.:second',(req,res)=>{
    const {first, second} = req.params
   res.send(`first: ${first} second : ${second}`);
})

//with regex
app.get('/student/product/:id([0-9]{2})',(req,res)=>{
    const {id} = req.params
    res.send(`Your id is ${id}`)
})

//we can write post or title at :post .
app.get('/:post(post|title)/:title',(req,res)=>{
    const {post,title} = req.params
    res.send(`Your post is : ${post}  and ${title}`)
});


//app.params
//name id params is same in students id;
app.param('id',(req,res,next, id)=>{
    console.log(`${id}`);
    next()
})
app.get('/students/:id',(req,res)=>{
    const {id} = req.params
    console.log(`${id}`)
    res.send(`This is a ${id}`);
})


//app params == array of root parameters.
app.param(['id','page'],(req,res,next, value)=>{
    console.log(`Called only onced . ${value}`);
    next()
})
app.get('/studentArray/:id/:page',(req,res)=>{
    res.send(`Response ok.`);
    console.log('It your times ')
})

//Query string.
app.get('/params',(req,res)=>{
    console.log(req.query);
    res.send("Response Ok.");
});


app.listen(port,()=>{
    console.log("Server Connected Successfully.");
});

//if / slash , dot . or - hyphen same in url .

Comments

Popular posts from this blog

My Sql Query ..

Interview question laravel.