Next.js 13 Bagaimana untuk mendapatkan kuki pada sisi klien dan pelayan
P粉690200856
P粉690200856 2024-04-01 11:22:43
0
1
761

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粉690200856
P粉690200856

membalas semua(1)
P粉470645222

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;
};
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan