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

Axios请求Authorization未达后端致401,Postman请求正常

Axios请求Authorization头后端丢失问题排查与解决

问题描述

使用Axios发起GET请求时,浏览器Network面板中能看到Authorization请求头正常携带,但后端始终接收不到,返回401状态码及错误信息{"error": "Missing access token"};使用Postman发起完全相同的请求(相同URL、相同Authorization头),后端能正常接收并返回数据。

代码示例

export const fetchContactsAxios = createAsyncThunk(
  'contacts/fetchContacts',
  async (credentials: { user_id: string; }, { getState }) => {
    try {
      axios.defaults.withCredentials = true;
      const state = getState() as RootState;
      const token = state.apiAuth?.accessToken;

      if (!token) {
        throw new Error('Token not found in state');
      }

      const { user_id} = credentials;

      const headers = {
        Authorization: 'Bearer ' + token,
        withCredentials: true,
      };

      console.log('Headers:', headers);
      console.log(
        'Request URL:',
        `${API_URL}/api/users/contacts?user_id=${user_id}`,
      );

      const response = await axios.get(
        `${API_URL}/api/users/contacts?user_id=${user_id}`,
        { headers },
      );

      console.log('Response Data:', response.data);
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error)) {
        console.error('Axios error response:', error.response?.data);
      }
      console.error('Error fetching contacts:', (error as Error).message);
      throw error;
    }
  },
);

排查与解决步骤

1. 移除请求头中的withCredentials配置

withCredentials是Axios请求配置的顶级属性,不属于请求头字段。将其放在headers对象中会被当作普通请求头发送,可能导致Axios内部配置冲突,进而影响Authorization头的正常传递。

修改后的请求配置:

const response = await axios.get(
  `${API_URL}/api/users/contacts?user_id=${user_id}`,
  { 
    headers: { Authorization: 'Bearer ' + token },
    withCredentials: true // 移到顶级配置
  },
);

同时建议移除全局的axios.defaults.withCredentials = true,避免影响其他不需要携带凭证的请求,改为在需要的请求中单独配置。

2. 检查Axios请求拦截器

如果项目中配置了Axios请求拦截器,需确认拦截器是否存在篡改、移除Authorization头的逻辑。例如某些拦截器可能在特定条件下覆盖或删除请求头,可临时禁用拦截器测试,或检查拦截器代码是否存在类似错误逻辑:

// 错误示例:意外覆盖请求头导致Authorization丢失
axios.interceptors.request.use(config => {
  config.headers = {};
  return config;
});

3. 验证后端CORS配置

浏览器的CORS机制会对跨域请求的头信息进行校验,后端需确保以下配置正确:

  • Access-Control-Allow-Headers包含Authorization字段
  • 如果使用withCredentials,需设置Access-Control-Allow-Credentials: true
  • Access-Control-Allow-Origin不能设为*,必须指定前端的具体域名(如http://localhost:3000)

4. 使用独立Axios实例避免配置冲突

全局修改Axios默认配置容易引发冲突,建议创建独立的Axios实例用于认证请求:

const authAxios = axios.create({
  withCredentials: true,
  baseURL: API_URL
});

// 后续请求使用该实例
const response = await authAxios.get(`/api/users/contacts?user_id=${user_id}`, {
  headers: { Authorization: 'Bearer ' + token }
});

内容的提问来源于stack exchange,提问作者Andrii Spivak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 20:55:07