首页 > 解决方案 > git api 在执行 axios 调用时返回 401 未经授权的错误,但 curl 返回 200

问题描述

axios 对 git api 的调用返回 401,但是使用相同的标头卷曲相同的 url 返回 200 和正确的数据,有人知道为什么吗?

axios调用返回401

let headers = {
    "Authorization": "token abc",
    "Accept" : "application/json",
    "Content-Type": "application/json"
}

    await axios.get("SOME_GIT_API_URL", headers)
      .then((data) => {
        console.log(data.data)

      })
      .catch((err) => {
        console.log(err)
      })

卷曲返回 200

curl --location --request GET "SOME_GIT_API_URL" --header 'Authorization: token abc'

标签: javascriptgitapiaxiosfetch

解决方案


在 axios 上,标题键必须在对象内部。您的标头变量未包含该“标头”作为键。例子 :

// header inside an object
const headerObject = {
  header: {
    "Authorization": "token abc",
    "Accept" : "application/json",
    "Content-Type": "application/json"
  }
}

await axios.get("SOME_GIT_API_URL", headerObject)
  .then((data) => {
    console.log(data.data)
  })
  .catch((err) => {
     console.log(err)
  })

推荐阅读