【问题标题】:POST request in Axios retuning 401 UnauthorisedAxios 中的 POST 请求重新调整 401 Unauthorized
【发布时间】:2020-02-02 22:21:57
【问题描述】:
async create() {
  const data = {
    name: this.name
  };
  const headers = {
    "Content-Type": "application/json",
    Accept: "application/json",
    Authorization: `Bearer ${this.token}`
  };
  axios
    .post("URL", data, headers)
    .then(res => {
      console.log('SUCCESS');
    })
    .catch(err => console.log(err.response));
}

来自登录组件的令牌。令牌已正确加载,因为在 Postman 中尝试 POST 请求返回成功但 axios 调用返回

{ message: 'Unauthenticated.' },
  status: 401,
  statusText: 'Unauthorized'

任何指针都可以识别此错误的方向或根源。

【问题讨论】:

  • 是 CORS 请求吗?我建议在浏览器的开发者工具的网络选项卡中深入了解请求的详细信息。
  • 您可以通过单击邮递员请求窗口上的“代码”来获得一个非常好的示例,以了解邮递员作为 JavaScript 代码发送的内容。希望这会对您有所帮助 - 否则解决问题有点复杂。
  • 也许您可以尝试向PostMan Echo发送相同的请求,至少您会知道您的参数是否正确到达,了解问题是在客户端还是服务器上。
  • 您确定调用时 this.token 已正确加载吗?尝试在调用之前创建一个 console.log 或设置断点

标签: vue.js axios nativescript


【解决方案1】:

您错误地将标头传递给 axios。试试这个:

const headers = {
    "Content-Type": "application/json",
    Accept: "application/json",
    Authorization: `Bearer ${this.token}`
};

axios.post(URL, data, { headers })

这就是为什么您的 Authorization 标头未包含在您的请求中并且服务器返回 401 的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 2018-04-28
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多