代码之家  ›  专栏  ›  技术社区  ›  Rod

如何向router.get添加查询参数

  •  1
  • Rod  · 技术社区  · 7 年前

    嗨,我想添加一个查询参数到我的router.get,但我不知道如何定义它。

    现在是这样工作的:

    http://test.com/path1/path2/1
    
    router.get('/path1/path2/:userId', (req, res) => {
        let route = `GET /path1/path2/${req.params.userId}`;
    

    http://test.com/path1/path2/1?q=test
    

    在router.get中如何定义?

    3 回复  |  直到 7 年前
        1
  •  2
  •   pzaenger lio    7 年前

    您不需要直接向路由添加查询参数。只要保持 /path1/path2/:userId

    在您的功能范围内,您可以检查 query parameter 存在,这里通过 req.query.q .

    // http://test.com/path1/path2/1?q=test
    router.get('/path1/path2/:userId', (req, res) => {
        let route = `GET /path1/path2/${req.params.userId}`;
    
        // If http://test.com/path1/path2/1, req.query.q is undefined
        console.log(req.params.userId, req.query.q);
    });
    
        2
  •  1
  •   jfriend00    7 年前

    你使用 req.query

    所以,对于URL http://test.com/path1/path2/1?q=test ,可以得到如下查询参数:

    router.get('/path1/path2/:userId', (req, res) => {
        console.log(req.params.userId);        // "1"
        console.log(req.query.q);              // "test"
    });
    

    here .

        3
  •  1
  •   front_end_dev    7 年前

    http://test.com/path1/path2/1?q=test

    访问路径参数= req.params.userId .

    访问查询参数= req.query.q

    阅读更多Express文档

    http://expressjs.com/de/api.html#req.query

    http://expressjs.com/de/api.html#req.params

    推荐文章