Sol*_*tos 5 javascript redirect reactjs next.js
鉴于业务定义:
鉴于业务需求:
// next.config.js
module.exports = {
...
async redirects() {
return [
{
source: "/:personName((?:[A-Z][a-z]+){2})",
destination: "/profile/:personName",
permanent: true
}
]
Run Code Online (Sandbox Code Playgroud)
此代码应仅匹配 PascalCase,并且/profile/:personName仅在存在肯定匹配时才重定向到。
它不起作用,因为写入时/about它被重定向到/profile/about. 这里有一个 SSCCE 沙箱https://codesandbox.io/s/redirects-not-working-as-expected-6z909
对不是来自 Nextjs 或我们的页面列表的任何内容进行负向前瞻。但 PascalCase 命名尚未实现
// next.config.js
module.exports = {
...
async redirects() {
return [
{
source: "/:personName((?!_next|about|profile).+)", // not maintainable
destination: "/profile/:personName",
permanent: true
}
]
Run Code Online (Sandbox Code Playgroud)
这是一个SSCCE工作示例codesandbox https://codesandbox.io/s/redirects-working-with-negative-lookahead-bi9xf?file=/next.config.js
redirects()可以通过拦截名为或 的getServerSideProps页面的所有请求来拦截服务器的功能,如下例所示[anyName].js[...anyName].js
// [...root].js
const personNameRegexp = /^(?:[A-Z][a-z]+){2}$/;
export const getServerSideProps = async ({ params }) => {
const isPersonName = personNameRegexp.test(params.root);
if (isPersonName) {
return {
redirect: {
destination: `profile/${params.root}`,
permanent: false
}
};
}
return {
props: {}
};
};
Run Code Online (Sandbox Code Playgroud)
这是一个 SSCCE 工作示例codesandbox https://codesandbox.io/s/redirections-based-on-regex-cmn6c
我尝试使用这些has对象,但personName显然不是查询参数,并且不能像这样匹配:
has: [
{
type: "query",
key: "personName",
value: "(?:[A-Z][a-z]+){2}",
},
],
Run Code Online (Sandbox Code Playgroud)
next.config.jssredirects()函数中实现这一点吗?| 归档时间: |
|
| 查看次数: |
1638 次 |
| 最近记录: |