javascript - Express JS - 包括可选参数不起作用
问题描述
我在进行分页时遇到问题。当包含多个&
参数时。简单地说,它不起作用。
server.get("/search", async(req, res) => {
try {
const key = req.query.key;
const value = req.query.value;
const text = req.query.text;
let result = await collection.aggregate([
{
'$search': {
'text': {
'query': `${text}`,
'path': 'title'
}
}
},
//match key here...
]).toArray();
res.send(result)
} catch (error) {
console.error(error)
}
})
解决方案
The problem you have there is how you structured your endpoint url.
app.get("/search/:text/:key?&:value?&.....", (req,res)) => {....}
If you want to get the values you send via query string, you don't have to add the query params to the endpoint's url, you can simply have it like so:
app.get("/search", (req,res)) => {....}
And then build the request to the API like this:
http://localhost:4000/search?text=mango&brand=rasna
Like this you can access the properties of the request in the route's controller:
app.get("/search", (req,res)) => {
const { text, brand } = req.query;
}
Optional values are fine, if you don't send them they will be undefined when you try to access their values in the controller so you can just check for them with conditionals.
app.get("/search", (req, res)) => {
const { text, brand } = req.query;
if(text) { ... }
if(brand) { ... }
}
Obviously this is a very simple implementation just to explain the problem.
推荐阅读
- vue.js - Vite: img src 别名在作为组件道具传递时不起作用
- python - 如何删除 flask_session 会话?
- linkedin - 如何在LinkedIn中检索公司最近的帖子?
- python - google colab-lxml 的构建轮(setup.py)...错误错误:lxml 的构建轮失败
- python - “帮助”命令(Defectio.py,类似于 discord.py)
- azure-ad-b2c-custom-policy - 重置密码允许将验证码发送到任何电子邮件。如何强制检查电子邮件是否作为用户 Azure B2C 帐户存在?
- autohotkey - AHK 按类型对文件进行分组
- java - Worker 如何在发送通知之前检查活动是否处于活动状态
- firebase - 如何将 Firebase 的 Google 登录集成到具有不同编程环境的 Flutter 项目中?
- python - ConnectionError: ('Connection aborted.', ConnectionResetError(10054, '现有连接被远程主机强行关闭', None, 10054, None))