我正在使用 next.js 并尝试使用中间件。如果cookies没有token,则意味着没有用户,因此任何人都不应访问特定页面作为个人资料。但就我而言,当我没有令牌并写入 url
/profile
时,我可以看到个人资料页面。你能告诉我我做错了什么吗?谢谢
import { NextResponse, NextRequest } from 'next/server';
export async function middleware(req) {
try {
const path = req.nextUrl.pathname;
const isPublicPage =
path === '/login' ||
path === '/register' ||
path === '/' ||
path === '/signOutPage';
const token = req.cookies.userToken;
console.log('token >>>', token);
if (token === undefined && !isPublicPage) {
return NextResponse.redirect(new URL('/login', req.nextUrl.href));
}
if (token && token.length > 15 && isPublicPage) {
return NextResponse.redirect(new URL('http://localhost:3000/login', req.nextUrl.href));
}
return NextResponse.next();
} catch (error) {
return NextResponse.error();
}
}
export const config = {
matcher: ['/', '/login', '/register', '/signOutPage'],
};
这是我的文件夹和文件的结构
components
modules
pages
reduxFile
styles
utils
middleware.js // here is middleware, here I am getting response
// if I put middleware to pages folder, I did not see any response in terminal
您的中间件未针对
/profile
路由进行配置。您可以在匹配器中使用通配符让它在所有路由上运行:
export const config = {
matcher: ['/:path*'],
};
您可以使用正则表达式来避免匹配某些路径,这样您就不必在源代码中处理排除的页面。更多信息这里。