Next.js 13 如何在客户端和服务器端获取cookie
P粉690200856
P粉690200856 2024-04-01 11:22:43
0
1
784

我有一个函数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粉690200856
P粉690200856

全部回复(1)
P粉470645222

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

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;
};
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板