在nextjs客户端获取cookie

yrdbyhpb  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(176)

我试图检查是否存在特定的cookie,如果不存在,就从redux中删除一些数据,但即使使用了一个名为“cookies-next”的软件包,我也无法获得cookie。
我使用客户端组件来改变redux中的状态。任何人都知道如何在客户端获得cookie,有或没有一个包?

niknxzdl

niknxzdl1#

使用Cookie-下一个包

import { getCookie } from 'cookies-next';
const cookieValue = getCookie('cookie_name');

没有任何包裹

const cookieValue = document.cookie.split('; ')
  .find(row => row.startsWith('cookieName='))
  ?.split('=')[1];

您可以使用document. cookie访问cookie。

ubof19bj

ubof19bj2#

你可以试试下面的代码:

import { NextRequest, NextResponse } from "next/server";
type RequestBody = {
  email: string;
  password: string;
};

export async function POST(request: NextRequest) {
  const body: RequestBody = await request.json();
  const value = {
    email: body.email,
    password: body.password,
  };
  const res = await fetch("https://127.0.0.1:8000/api/auth/login", {
    method: "POST",
    mode: "cors",
    cache: "no-cache",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(value),
  });
  const data = await res.json();
  if (data.success) {
    // Then set a cookie
    const response = NextResponse.json(
      {
        success: data.success,
      },
      { status: 200 }
    );

    response.cookies.set({
      name: "login",
      value: "true",
      httpOnly: true,
    });
    response.cookies.set({
      name: "access_token",
      value: data.access_token, //token value here
      httpOnly: true,
      maxAge: data.expires_in,
    });
    return response;
  }
  return new NextResponse(null, {
    status: 404,
    statusText: "Bad request",
    headers: {
      "Content-Type": "text/plain",
    },
  });
}

在app/API/users/route.ts之后,可以获取cookie

import { NextRequest, NextResponse } from 'next/server'
type ResponseBody = { errors: { message: string }[] } | { username: string };
async function getUserByValidSessionToken(token : string){
  
    const res = await fetch('http://127.0.0.1:8000/api/auth/user-profile',{
         headers: {
           "Content-Type": "application/json",
           "Authorization":"Bearer "+token
         },
    });
   
    const data = await res.json();
    return {
      username: data.name
    }
}

export async function GET(
    request: NextRequest
  ): Promise<NextResponse<ResponseBody>> {
    const token = request.cookies.get("access_token");
    const user = !token?.value
      ? undefined
      : await getUserByValidSessionToken(token.value);
  
    if (!user) {
      return NextResponse.json({
        errors: [{ message: "User not found by session token" }],
      });
    }
  
    return NextResponse.json({
      username: user.username,
    });

在文章中的例子,你可以看到它:Check Login Using Middleware With NextJS 13

相关问题