我有一个函数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}”服务器端
您可以根据窗口对象的当前类型有条件地导入每个模块。如果未定义;导入服务器模块,如果不是客户端模块: