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

如何在React中使用axios读取图片请求的自定义响应头prediction

解决方案

问题原因

你拿不到prediction响应头和设置的responseType为arraybuffer/blob没有关系,是浏览器CORS规则的默认限制:默认仅允许前端访问6种基础响应头,自定义响应头需要后端主动声明暴露后才能被前端读取。

后端配置修改(FastAPI侧)

在FastAPI的CORSMiddleware配置中添加expose_headers参数,将需要暴露的自定义响应头prediction加入列表即可,配置示例如下:

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

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    # 其余原有配置保持不变即可
    allow_origins=["你的前端域名"], # 生产环境不建议用通配符*
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    # 新增如下配置
    expose_headers=["prediction"]
)

前端读取方式

后端配置生效后,直接从axios响应的headers对象中读取该字段即可,推荐用get方法获取更稳妥:

// 原有请求逻辑保持不变
.then(response => {
  // 读取prediction头
  const predictionResult = response.headers.get('prediction')
  console.log(predictionResult) // 即可拿到COVID - 19等返回值
  // 原有图片处理逻辑保持不变
  let base64ImageString = Buffer.from(response.data, 'binary').toString('base64')
  let srcValue = "data:image/png;base64,"+base64ImageString
  setImage(srcValue)
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:45:01