React axios未经授权...为什么

li9yvcax  于 2023-03-29  发布在  iOS
关注(0)|答案(1)|浏览(155)

我有一个简单的问题。为什么我有错误401(未经授权)。令牌是正确的。这个方法运行后点击按钮

const getFile = (filename) => {  //filename = "wy8NNSV9uAvL0NPYydw5iaZDkz5XQYeFo2A7VZo0.pdf"
axios.get(
    "http://localhost:8000/api/files/" + filename, {},
    {
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token"),
        responseType: "blob",
      },
    }
  )
  .then((res) => {
    const file = new Blob([res.data], { type: "application/pdf" });
    const fileURL = URL.createObjectURL(file);
    window.open(fileURL);
  })
  .catch((err) => {
    console.log(err);
  });};

After click button

t0ybt7op

t0ybt7op1#

Axios get方法只需要2个参数。
尝试从:

axios.get(uri, data, config) 
// which is the syntax for post request

收件人:

axios.get(uri, config)

在您的代码中:

const getFile = (filename) => {
axios.get(
    "uri" + filename, // here remove: {},
    {
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token"),
        responseType: "blob",
      },
    }
  )
  .then((res) => {
    // ..
  })
  .catch((err) => {
    console.log(err);
  });
};

相关问题