Next.js 13 如何在客戶端和伺服器端取得cookie
P粉690200856
P粉690200856 2024-04-01 11:22:43
0
1
758

我有一個函數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;
};
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板