简体   繁体   中英

Extract query in node.js

Given this url /calculatePrice?id[0]=123&qty[0]=2&id[1]=456&qty[1]=3 . I am building this to extract the queries:

app.use('/calculatePrice', (req,res) => {
var query = {};
query.id = [];
query.qty = [];
    if(req.query.id[i]) query.id.push(req.query.id[i]);
    if(req.query.qty[i]) query.qty.push(req.query.qty[i]);
console.log(query);
}

but it doesn't work. How can I extract these queries right ?

Using Express.js you can access to query params at req.query directly.

app.use('/calculatePrice', (req,res) => {
  const params = req.query;
  const id = params.id || [];
  const qty = params.qty || [];

  console.log(id);
  console.log(qty);

  ...
}

ES6 way using destructuring:

app.use('/calculatePrice', (req,res) => {
  const { id, qty } = req.query;

  console.log(id);
  console.log(qty);

  ...
}

*Edit: I have just checked in Express.js v.4 and for passing array elements it can be done setting the index in the array if you want to set the position in the array of the param:

/calculatePrice?id[1]=123&qty[1]=2&id[0]=456&qty[0]=3

req.query = {
  id: [456, 123],
  qty: [3, 1],
}

Or if you want to save them in the same order they are sent, like this:

/calculatePrice?id[]=123&qty[]=2&id[]=456&qty[]=3

req.query = {
  id: [123, 456],
  qty: [1, 3],
}

or

/calculatePrice?id=123&qty=2&id=456&qty=3

req.query = {
  id: [123, 456],
  qty: [1, 3],
}

I have just figured this out myself. I can actually use this:

app.use('/calculatePrice', (req,res) => {
var query = {};
    if(req.query.id) query.id = req.query.id;
    if(req.query.qty) query.qty = req.query.qty;
console.log(query);
});

This will return { id: [123,456] , qty: [2,1] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM