You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Bearer Token调用API返回401未授权,请求排查问题

问题描述

我已尝试3天,仍无法通过Bearer Token从API获取数据。以下是我的代码:

const token = "MYOTKEN";
function App() {

  const body = {
    product: {
      somerandombody,
    },
  };
axios
    .get("http://upayments-studycase-api.herokuapp.com/api/products", body, {
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + token,
      },
    })
    .then((response) => {
      console.log("response", response.data);
    })
    .catch((error) => {
      console.log("error", error.response);
    });

返回的错误信息如下:

error 
{data: {…}, status: 401, statusText: 'Unauthorized', headers: AxiosHeaders, config: {…}, …}
config
: 
{transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
data
: 
{message: 'not authorized', stack: null}
headers
: 
AxiosHeaders {content-length: '41', content-type: 'application/json; charset=utf-8', Symbol(defaults): null}
request
: 
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status
: 
401
statusText
: "Unauthorized"
[[Prototype]]
: Object

我需要通过Bearer Token成功获取API数据,请问我哪里操作有误?

问题排查与解决

1. 修正GET请求的参数格式

Axios的get方法参数顺序为url[, config],你错误地将body作为第二个参数传入。GET协议规范中不允许携带请求体,这会导致请求格式异常,服务器无法正确解析请求,进而返回401未授权错误。

正确写法需移除body参数,直接传入配置对象:

const token = "MYOTKEN";
function App() {
axios
  .get("http://upayments-studycase-api.herokuapp.com/api/products", {
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + token,
    },
  })
  .then((response) => {
    console.log("response", response.data);
  })
  .catch((error) => {
    console.log("error", error.response);
  });
}

2. 验证Token的正确性

  • 检查MYOTKEN是否存在拼写错误(比如疑似笔误的MYOTKEN应为MYTOKEN)。
  • 确认Token是否处于有效期内,以及是否拥有访问该/api/products端点的权限。

3. 确认请求头格式

确保Authorization头的格式完全正确:Bearer 与Token之间仅保留一个空格,无多余字符或空格。

内容的提问来源于stack exchange,提问作者Hazal Kaya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 12:20:54