Asked 7 years ago
5 Feb 2017
Views 1220
yogi

yogi posted

how to process Query String (GET/POST) in express framework in node JS

how to process the query string so it can be dynamic element in query string in express.js(express framework) in Node Js


http://127.0.0.1:3000/product/123/detail


for example in above URL product id is dynamic so i need to make proper request handler which handle dynamic request URL.
So how to do make request handler in Express Framework at Node Js.
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

two request sample
1. GET

app.get('/product:id',function(req,res){
    
});

here we passing id of product dynamically

2. POST

app.post('/add',function(req,res){

});



how to get request query string .

req.params get access of query string .

app.get('/product:id',function(req,res){
    console.log(req.params.id) 
});

for http://127.0.0.1:3000/product/124 , req.params.id give use 124

for the post value we need body parser
so import it by npm command

npm install body-parser



at code
first load body-parser module

var bodyParser = require('body-parser');

now use it

app.use(bodyParser());


now get post body

app.post('/add',function(req,res){
  console.log(req.body.item);
});

where request.body.postParameterName

Middleware for handling multipart/form-data is multer .

3. all

The app.all() method is useful for mapping “global” logic for specific path prefixes or arbitrary matches


app.all('*', requireAuthentication);

it means it need to run requireAuthentication for all request .
Rasi

Rasi
answered Nov 30 '-1 00:00

req also use to store some temporary access or data in express framework .


app.use(function(req,res, next){
    req.db = db;
    next();
});

where db have instance of database
so suppose if we want to share that with other request processor than i can do it with req.db=db so it will be available on all request.

so suppose router.js


// GET produce list page.
router.get('/produce_list', function(req, res){
    var db = req.db;

    db.all("SELECT id, name FROM employee", function(err, produce){
        if(err !== null){
            console.log(err);
        }
        else{
             console.log(produce);
        }
    });

});

here you can see get the db instance from request in express framework
Post Answer