NextJS Middleware TypeError: NetworkError when attempted to fetch resource

问题描述 投票:0回答:0

我正在学习一个旧教程,该教程在 NextJS 中设置了一个中间件,它们端的代码似乎工作正常,但相同的代码块在我端导致了 NetworkError。问题可能是由于中间件干扰了 NextJS 或 webpack 管理器,因为这些在我的代码重定向的页面的开头发出请求,导致页面无法加载,但我不知道如何排除来自中间件的这些请求。

我正在尝试实现一个基本的中间件,如果用户尚未登录或会话已过期,则在他们尝试将页面加载到登录页面时重定向用户。

import { getToken } from "next-auth/jwt";
import { NextResponse } from "next/server";

export async function middleware(req, res) {
    // token will exist if user is logged in
    const token = await getToken({ req, secret: process.env.JWT_SECRET });
    
    const url = req.nextUrl.clone();
    const { pathname } = req.nextUrl;

    // allow the request if the following is true...
    // 1. the token exists
    // 2. it's a request for next-auth session & provider fetching
    
    console.log("url: ", url.href);

    if (pathname.includes("/api/auth") || token) {
        console.log("login");
        return NextResponse.next();
    };

    // redirect to login if no token AND requesting protected route
    if (!token && pathname !== "/login") {
        console.log("redirect: ", pathname);
        return NextResponse.redirect(`${url.host}/login`);
    };

    console.log("fail: ", pathname);
}

我已经尝试过这段代码来对来自 NextJS 本身的请求进行例外处理:

if (pathname.includes("/_next")) {
    return NextResponse.next();
}

但是没用。

javascript reactjs webpack next.js middleware
© www.soinside.com 2019 - 2024. All rights reserved.