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

React中使用Axios无法获取自定义Header问题求助

问题原因及解决办法

原因

浏览器的CORS安全机制默认仅允许前端JavaScript访问简单响应头(如Content-Type、Cache-Control等),自定义Header属于非简单响应头。如果后端未明确配置允许暴露该Header,即使浏览器能在开发者工具中看到,Axios也无法通过response.headers读取到。

解决办法

1. 后端FastAPI配置:暴露自定义Header

在FastAPI的CORSMiddleware中,通过expose_headers参数指定需要暴露的自定义Header名称:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# 允许的前端源,根据实际情况修改
origins = ["http://localhost:3000"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["X-Header-Custom"]  # 关键:添加自定义Header到暴露列表
)

# 示例接口,返回自定义Header
@app.get("/api/example")
async def example_endpoint():
    return {"data": "test"}, {"X-Header-Custom": "your-custom-value"}

2. 前端Axios读取注意事项

  • 浏览器会自动将响应头名称转换为小写,所以读取时要使用小写的键名:
  • 如果请求需要携带凭证(如Cookie),需开启withCredentials: true(配合后端的allow_credentials=True)
axios.get("http://localhost:8000/api/example", {
  withCredentials: true  // 可选,根据是否需要凭证决定
})
.then(response => {
  // 注意这里是小写的x-header-custom
  console.log("自定义Header值:", response.headers['x-header-custom']);
})
.catch(err => console.error(err));

补充说明

开发者工具能看到自定义Header是因为工具直接获取了原始响应数据,不受CORS的暴露限制;而前端JavaScript受同源策略约束,只能访问后端明确允许暴露的Header。

内容的提问来源于stack exchange,提问作者Leonardo Radillo escobar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 11:47:38