简体   繁体   中英

Node/Express Request Query

I have an endpoint that looks like this.

// GET /api/logs/
app.get('/api/logs', function (request, response) {
  if (request.query.reverse === true) {
    response.send((mainModule.logs).reverse());
  }
  else {
    response.send(mainModule.logs);
  }
});

The response is an array of objects, and I want the order to be determined by the query param 'reverse' boolean. Right now the query doesn't appear to be doing anything. What am I doing wrong? Thanks!

Querystring values are always returned as strings, so you should check for reverse === 'true' rather than reverse === true . This is because Express's req.query pulls directly from Node's querystring parser (code here ). If you run the following in Node, you'll see that the result returns a string rather than a boolean for the reverse parameter.

var query = require('querystring').parse('reverse=true');
console.log(query); // returns { reverse: 'true' }

Note that using request.query.reverse == true won't work. Both == and === will return false. So you'll need to do either == 'true' or ==='true' .

https://github.com/jackypan1989/express-query-parser

help you to covert all ambiguous string values

Normally you may call http://localhost/?a=null&b=true&c[d]=false .

And get req.query = {a: 'null', b: 'true', c: {d: 'false'}}

This project will help you parse to correct value.

req.query = {a: null, b: true, c: {d: false}}

do a

 console.log(typeof request.query.reverse );

I think it's a string but you are checking if the value matches boolean and is true. Either parse the value to boolean or do

if (request.query.reverse == true)

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