首页 > 解决方案 > 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)
    }
})

标签: javascriptexpress

解决方案


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.


推荐阅读