next.js 我需要从route.js中的GET调用API获取cookie

wa7juj8i  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(131)

我在Next.js 13中创建了一个网站,并有一个名为/api/users/me的路由。在那个路由里面,我必须得到饼干来提取令牌。当我从浏览器调用路由API时,我得到了我想要的结果,但是当我试图从前端页面调用它时,它在cookie中为null
在src/api/users/me/route.js

import { NextResponse, NextRequest } from "next/server";
import { connectDB } from "@/dbConfig/dbConfig";

connectDB();

export async function GET(request) {

  try {

    console.log("Token is: ", request.cookies); // expect to get cookies, but null
    return NextResponse.json({ msg: "success" }, { status: 200 });
  } catch (error) {
    return NextResponse.json(
      { msg: "can't get data", err: error.message },
      { status: 500 }
    );
  }
}

字符串
在src/app/profile/page.jsx中

import UserDetails from "@/components/UserDetails";
import { cookies } from "next/headers";

async function getData() {
  const cookieStore = cookies();
  const token = cookieStore.get("token"); // here i get the cookies
  try {
    console.log(token.value);
    const res = await fetch(`http://localhost:3000/api/users/me`, {
      headers: {
        userToken: String(token.value), // try to pass it in the headers
      },
    });
    if (!res.ok) {
      throw new Error("Failed to fetch data, please try another time");
    }

    return res.json();
  } catch (error) {
    console.log("Error loading topic", error);
      }
}

async function ProfilePage() {
  const data = await getData();

  return (
    <div className="flex flex-col justify-center items-center min-h-screen">
      <h1 className="font-bold text-3xl">Profile page</h1>
      <p className="text-gray-600">This is the profile page</p>
      <UserDetails />
    </div>
  );
}

export default ProfilePage;

f45qwnt8

f45qwnt81#

您没有创建有效的API路由。API路由应该在route.js文件中定义。
src/api/users/me.js移动到src/app/api/users/me/route.js
对于cookie,请查看此文档-https://nextjs.org/docs/app/building-your-application/routing/router-handlers#dynamic-functions

import { cookies } from 'next/headers'
 
export async function GET(request: Request) {
  const cookieStore = cookies()
  const token = cookieStore.get('token')
 
  return new Response('Hello, Next.js!', {
    status: 200,
    headers: { 'Set-Cookie': `token=${token.value}` },
  })
}

字符串

相关问题