首页 > 解决方案 > 如何使用 swr 发送标头

问题描述

我正在尝试使用SWR和 Axios 发送标头,但没有发送标头。

 const fetcher = (url) =>
    axios
      .get(url, { headers: { Authorization: "Bearer " + auth.token } })
      .then((res) => res.data);
  const { data, error } = useSWR(
    `http://localhost:8000/api/v1/users/get-avatar`,
    fetcher
  );
  if (error) console.log(error);
  if (data) console.log(data);

使用 SWR 发送标头的正确方法是什么?

标签: reactjsswr

解决方案


根据文档https://swr.vercel.app/docs/arguments你应该做

const fetcher = (url, token) =>
    axios
      .get(url, { headers: { Authorization: "Bearer " + token } })
      .then((res) => res.data);

const { data, error } = useSWR(
  [`http://localhost:8000/api/v1/users/get-avatar`, auth.token],
  fetcher
);
if (error) console.log(error);
if (data) console.log(data);

推荐阅读