简体   繁体   English

节点/表达请求查询

[英]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. 响应是一个对象数组,我希望由查询参数“ reverse”布尔值确定顺序。 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 . Querystring值始终以字符串形式返回,因此您应检查reverse === 'true'而不是reverse === true This is because Express's req.query pulls directly from Node's querystring parser (code here ). 这是因为Express的req.query直接从Node的querystring解析器( 此处的代码)中提取。 If you run the following in Node, you'll see that the result returns a string rather than a boolean for the reverse parameter. 如果在Node中运行以下命令,您将看到结果为reverse参数返回一个字符串而不是布尔值。

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

Note that using request.query.reverse == true won't work. 请注意,使用request.query.reverse == true无效。 Both == and === will return false. =====都将返回false。 So you'll need to do either == 'true' or ==='true' . 因此,您需要执行== 'true'==='true'

https://github.com/jackypan1989/express-query-parser 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 . 通常,您可以调用http:// localhost /?a = null&b = true&c [d] = false

And get req.query = {a: 'null', b: 'true', c: {d: 'false'}} 并获取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. 我认为这是一个字符串,但是您正在检查该值是否匹配布尔值并且为true。 Either parse the value to boolean or do 将值解析为布尔值或执行

if (request.query.reverse == true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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