Axios 未发送 headers、post 请求失败,收到 401

Axios not sending headers, post request failing, getting 401

我一直在使用 axios 从私有 API 获取一些数据,但现在我在从一个特定端点获取数据时遇到问题。

有趣的是,使用内置 fetch API,我收到了 200 响应,但与 axios 相同的请求不断重新调整 401 错误。知道可能是什么问题吗?

此代码有效:

const upVoteCommentTwo = async () => {
  console.log(localStorage.getItem("access_token"));
  try {
    const response = await fetch(
      `https://exammple.com/comments/${commentId}/vote/up`,
      {
        method: "POST",
        headers: {
          "X-API-KEY": "XXX",
          "Authorization": localStorage.getItem("access_token"),
        },
      }
    );

    console.log(await response.status);
  } catch (err) {
    console.log(err);
  }
};

这行不通:

const upVoteCommentOne = async () => {
  console.log(localStorage.getItem("access_token"));
  try {
    const response = await axios.post(
      `https://example.com/comments/${commentId}/vote/up/`,
      {
        headers: {
          "Content-Type": "application/json",
          "X-API-KEY": "XXX",
          "Authorization": localStorage.getItem("access_token"),
        },
      }
    );

    console.log(response.status);
  } catch (err) {
    console.log(err);
  }
};

问题出在 axios 的参数上。根据 documentation,一种有效的方法是使用以下顺序调用它:url,数据发送对象,请求配置对象。由于您似乎没有发送任何内容,因此您可以提供一个空对象作为数据,如下所示:

const response = await axios.post(
  `https://example.com/comments/${commentId}/vote/up/`,
  {},
  {
    headers: {
      "Content-Type": "application/json",
      "X-API-KEY": "XXX",
      "Authorization": localStorage.getItem("access_token"),
    },
  }
);

但是,根据GitHub中的issue,上述解决方案可能行不通。如果是这样,请尝试使用其他方式提出请求:

const response = await axios({
  method: "post",
  url: `https://example.com/comments/${commentId}/vote/up/`,
  headers: {
    "Content-Type": "application/json",
    "X-API-KEY": "XXX",
    "Authorization": localStorage.getItem("access_token"),
  },
  data: {},
});