搜索

首页  >  问答  >  正文

Next.js 13 如何在客户端和服务器端获取cookie

我有一个函数myFetch,它是fetch的包装器,用于在标头中添加令牌

import clientCookies from "js-cookie";
import {cookies} from "next/headers";

const myFetch = async (...args) => {
let token
if (typeof window === "undefined") {
  // client side
  token = clientCookies.get("authToken")
} else {
  // server side
  serverCookies = cookies()
  token = serverCookies.get("authToken").value
}

args[1].headers = {"Authorization": `bearer ${token}`}
const res = await fetch(...args)
const data = await res.json()
return data
}

但是我在客户端调用此函数时收到错误

You're importing a component that needs next/headers. That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.
Learn more: https://nextjs.org/docs/getting-started/react-essentials

有什么方法可以“仅从'next/headers'导入{cookies}”服务器端

P粉690200856P粉690200856237 天前713

全部回复(1)我来回复

  • P粉470645222

    P粉4706452222024-04-02 00:52:26

    您可以根据窗口对象的当前类型有条件地导入每个模块。如果未定义;导入服务器模块,如果不是客户端模块:

    const myFetch = async (...args) => {
      let token;
      if (typeof window === "undefined") {
        const { default: clientCookies } = await import("js-cookie");
        token = clientCookies.get("authToken");
      } else {
        const { cookies: serverCookies } = await import("next/headers");
        token = serverCookies().get("authToken").value;
      }
    
      args[1].headers = { Authorization: `bearer ${token}` };
      const res = await fetch(...args);
      const data = await res.json();
      return data;
    };
    

    回复
    0
  • 取消回复