Next JS 在重写中使用查询参数作为变量

Kri*_*ler 8 javascript reactjs next.js

使用 Next JS 我想将路径上的请求重定向/home?id=123qwert到新的目标路径/home/123qwert

我在从源中提取查询参数以在目标中再次使用时遇到问题。

这是我当前的实现:

    async rewrites() {
        return [
            /**
             * My source URL -> /home?id=123qwerty
             * My new destination -> /home/123qwerty
             */
            {
                source: '/home?id=:cmsId*',
                destination: '/home/:cmsId*'
            }
        ];
    }
Run Code Online (Sandbox Code Playgroud)

我的主页有一个动态页面设置/home/[id].js

我不断收到以下错误:

Reason: Unexpected MODIFIER at 5, expected END

  /home?id=:cmsId*
       ^

`source` parse failed for route {"source":"/home?id=:cmsId*","destination":"/home/:cmsId*"}
Run Code Online (Sandbox Code Playgroud)

jul*_*ves 1

您可以使用查询匹配,使用该has字段来匹配查询值的重写,并使用beforeFiles语法,以便匹配发生在文件系统检查之前。

async rewrites() {
    return {
        beforeFiles: [
            {
                 source: '/home',
                 has: [
                     {
                         type: 'query',
                         key: 'id',
                         value: '(?<cmsId>.*)' // Named capture group to match anything on the value
                     }
                 ],
                 destination: '/home/:cmsId'
             }
         ]
    };
}
Run Code Online (Sandbox Code Playgroud)