Rumah > Soal Jawab > teks badan
Saya mempunyai fungsi myFetch iaitu pembalut fetch untuk menambah token dalam pengepala
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 }
Tetapi saya mendapat ralat apabila memanggil fungsi ini di sisi pelanggan
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
Adakah terdapat sebarang cara untuk "mengimport {cookies} sahaja dari bahagian pelayan 'next/headers'"
P粉4706452222024-04-02 00:52:26
Anda boleh mengimport setiap modul secara bersyarat berdasarkan jenis semasa objek tetingkap. Jika tidak ditentukan; import modul pelayan, jika bukan modul klien:
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; };