如何在 Next.js 13.4 中间件中使用 Fetch API 发送 cookie 进行授权?

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

由于Axios无法在Next.js 13.4中间件中使用,因此我尝试使用Fetch API来实现授权。然而,我在使用 Fetch 发送 cookie 时遇到了困难。我知道 Fetch 默认情况下不会向服务器发送 cookie,因此我添加了选项“credentials: include”,但它仍然无法正常工作。您可以在下面找到 Next.js 中间件的源代码以及 Nest.js 后端的 CORS 配置。我遇到了类似的问题,但不幸的是,它没有为我的问题提供解决方案。即使包含凭据,Next.js 也不会通过获取请求发送 cookie

import { NextResponse } from "next/server";
    import type { NextRequest } from "next/server";
    const getUserRole = async function () {
      try {
        const res = await fetch("http://localhost:8080/auth/me", {
          method: "GET",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          credentials: "include",
        });
        if (res && res.status === 200) {
          return res.json();
        } else {
          console.error("Request failed");
        }
      } catch (error) {
        console.error('Request to "auth/me" failed', error);
      }
    };
    
    export function middleware(request: NextRequest) {
      const path = request.nextUrl.pathname;
      const isPublicPath =
        path === "/auth/login" || path === "/auth/register" || path === "/";
      const token = request.cookies.get("access_token")?.value || "";
    
      if (isPublicPath && token && path !== "/") {
        return NextResponse.redirect(new URL("/", request.nextUrl));
      }
    
      if (!isPublicPath && !token) {
        return NextResponse.redirect(new URL("/auth/login", request.nextUrl));
      }
    
      if (!isPublicPath && token) {
        console.log("tokkk :", token);
        getUserRole().then((res: any) => {
          console.log("role ::", res);
        });
      }
    }
    
    export const config = {
      matcher: ["/", "/auth/login", "/auth/register", "/dashboard"],
    };

 app.enableCors({
    origin: 'http://localhost:3000',
    allowedHeaders: [
      'Content-Type',
      'Authorization',
      'X-Requested-With',
      'X-HTTP-Method-Override',
      'Content-Type',
      'Accept',
      'Observe',
      'Access-Control-Allow-Credentials',
      'Access-Control-Allow-Origin',
      'Access-Control-Allow-Headers',
    ],
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
    credentials: true,
  });
javascript cookies authorization fetch-api next.js13
1个回答
0
投票

nextjs 中的中间件功能,只会在服务器上运行。如您所知,服务器上没有像浏览器中那样的 cookie 系统。所以,

credentials: "include"
不起作用。 因此,您需要将授权令牌重新分配给提取请求的标头。像这样:

export function middleware(request: NextRequest) {
    const token = request.cookies.get("access_token")?.value || "";

    const res = await fetch("http://localhost:8080/auth/me", {
        headers: {
            Authorization: token
        }
    })

    ...
}

您可以在 Mozilla 文档中找到有关

fetch()
函数的更多信息 https://developer.mozilla.org/en-US/docs/Web/API/fetch

© www.soinside.com 2019 - 2024. All rights reserved.