Express 中的查询参数
查询字符串 部分是 URL 在问号之后的部分 ?
,例如:
?answer=42
每个 key=value
pair 称为 查询参数 。 如果您的查询字符串有多个查询参数,它们由 &
连接,例如,下面的字符串有 2 个查询参数, a
和 b
。
?a=1&b=2
Express 会自动为您解析查询参数并将它们存储在 请求对象 中 req.query
.
const app = require('express')();
app.get('*', (req, res) => {
req.query; // { a: '1', b: '2' }
res.json(req.query);
});
const server = await app.listen(3000);
// Demo of making a request to the server
const axios = require('axios');
const res = await axios.get('http://localhost:3000/?a=1&b=2')
res.data; // { a: '1', b: '2' }
查询字符串中的对象和数组
如果一个查询参数在查询字符串中出现多次,Express 会将这些值分组到一个数组中。 例如,给定以下查询字符串:
?color=black&color=yellow
Express 将设置 req.query.color
到一个数组 ['black', 'yellow']
。
const app = require('express')();
app.get('*', (req, res) => {
req.query; // { color: ['black', 'yellow'] }
res.json(req.query);
});
const server = await app.listen(3000);
// Demo of making a request to the server
const axios = require('axios');
const querystring = '?color=black&color=yellow';
const res = await axios.get('http://localhost:3000/' + querystring);
res.data; // { color: ['black', 'yellow'] }
如果您在查询字符串参数中使用方括号,Express 会将该参数解析为对象。 例如,Express 会将下面的查询字符串解析为 { shoe: { color: 'white' } }
?shoe[color]=white
这种默认行为通常令人讨厌,并 可能导致安全漏洞 。 为了防止 Express 将方括号解析为对象属性,您应该设置 query parser
应用程序设置为 simple 。
const app = require('express')();
// Only parse query parameters into strings, not objects
app.set('query parser', 'simple');
app.get('*', (req, res) => {
req.query; // { color: ['black', 'yellow'], 'shoe[color]': 'white' }
res.json(req.query);
});
const server = await app.listen(3000);
// Demo of making a request to the server
const axios = require('axios');
const querystring = '?color=black&color=yellow&shoe[color]=white';
const res = await axios.get('http://localhost:3000/' + querystring);
res.data; // { color: ['black', 'yellow'], 'shoe[color]': 'white' }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论