Moh*_*bil 11 middleware reactjs next.js
如果使用 Spotify 的 API 没有可用令牌,我将使用 Next.js 中间件重定向到登录页面,
我的中间件如下所示:
import { getToken } from "next-auth/jwt";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export async function middleware(req: NextRequest) {
// const token = await getToken({ req, secret: process.env.JWT_SECRET });
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
const { pathname, origin } = req.nextUrl;
if (pathname.includes("/api/auth") || token) {
return NextResponse.next();
}
// console.log(origin);
// console.log(token);
if (!token && pathname != "/login") {
return NextResponse.redirect(new URL(`${origin}/login`));
}
}
Run Code Online (Sandbox Code Playgroud)
如果我注释掉这一部分:
if (!token && pathname != "/login") {
return NextResponse.redirect(`${origin}/login`);
}
Run Code Online (Sandbox Code Playgroud)
我不再收到错误,但显然,如果没有令牌,我需要此行进行重定向,我尝试检查是否有任何语法错误或任何错误,但我自己似乎找不到它,有什么帮助吗?
我收到的错误是这些:
Uncaught SyntaxError: expected expression, got '<'
react-refresh.js:1
Uncaught SyntaxError: expected expression, got '<'
webpack.js:1
Uncaught SyntaxError: expected expression, got '<'
main.js:1
Uncaught SyntaxError: expected expression, got '<'
_app.js:1
Uncaught SyntaxError: expected expression, got '<'
login.js:1
Uncaught SyntaxError: expected expression, got '<'
_buildManifest.js:1
Uncaught SyntaxError: expected expression, got '<'
Run Code Online (Sandbox Code Playgroud)
Ron*_*gee 17
问题是 Next.js 正在发出一些请求,/_next/*并且您将请求重定向到登录页面,这些请求是需要的,但永远不会完成。
您需要避免将任何请求重定向到 /_next/*
export const config = {
matcher: [
'/((?!_next|api/auth).*)(.+)'
],
}
Run Code Online (Sandbox Code Playgroud)
小智 13
我遇到了同样的问题,对我有用的解决方案是
export const config = {
matcher: "/",
};
Run Code Online (Sandbox Code Playgroud)
将此代码添加到您的 middleware.ts 文件中,这将解决问题:)
我遇到了同样的问题,这几乎解决了我的问题:
export const config = {
matcher: '/',
};
Run Code Online (Sandbox Code Playgroud)
我认为这是最新的 Next JS 版本附带的错误,上面的解决方案有帮助。另外降级到 Next JS 和 React 的另一个版本应该可以解决这个问题。
看起来这是 Next.js 最近出现的问题,希望他们能够修复它。
请参阅: https: //github.com/vercel/next.js/issues/38934#issuecomment-1193083803这似乎与您面临的问题相同。
同时,请尝试降级 Next.js 和 React.js 看看是否有帮助。
| 归档时间: |
|
| 查看次数: |
6482 次 |
| 最近记录: |