我有一個函數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}」伺服器端
您可以根據視窗物件的目前類型有條件地匯入每個模組。如果未定義;導入伺服器模組,如果不是客戶端模組: