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

节点express捕获url路径参数后的所有可选参数

  •  0
  • xpt  · 技术社区  · 3 年前

    跟进 Passing route control with optional parameter after root in express? , 我正在开发一个简单的url缩短应用程序,我想了解url路径参数之后的任何内容( /link/:id )转换为单个变量。例如,用于:

    http://localhost:3002/link/XYZ/abc/def?access_token=nQevH_hZSjs3qdOoLNnAIITwqd3lCdkq&expires_ in=7200&token_type=承载

    我希望 id=XYZ 然后 rest=abc/def?access_token=nQevH_hZSjs3qdOoLNnAIITwqd3lCdkq&expires_in=7200&token_type=Bearer

    我试过了 /link/:id/:rest? 但它不适用于示例url。

    router.get("/link/:id/:rest?", getLinkAndParams)
    
    // catch 404 and forward to error handler
    app.use(function (req, res, next) {
      next(createError(404));
    });
    
    exports.getLinkAndParams = async (req, res) => {
        const id = req.params.id
        let rest = req.params.rest
        rest = rest ? `/${rest}` : ""
    ...
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   zain ul din Muad1105    3 年前

    像这样:

    routes.get("/link/*", getLinkAndParams);

    示例:-

    router.get("/link/:id/*", getLinkAndParams);
    
    exports.getLinkAndParams = async (req, res) => {
      const id = req.params.id;
      const rest = req.params[0]; // the rest of the path and query string will be captured in this variable
      console.log(`id: ${id}`);
      console.log(`rest: ${rest}`);
      // ...
    };