【问题标题】:How to read image headers with React如何使用 React 读取图像标题
【发布时间】:2022-01-10 23:51:25
【问题描述】:

我有一个 API 可以查询以获取图像,其中有一些我想阅读的标题。 在 API(使用 fastAPI 构建)的文档中,我读到响应正文是图像,响应标头是这样的

 Response headers
 access-control-allow-credentials: true 
 content-type: image/png 
 date: Sun,05 Dec 2021 12:08:58 GMT 
 prediction: COVID - 19 
 server: uvicorn 
 transfer-encoding: chunked 

我想访问预测标头。

现在,当我通过 axios 和 React 发出请求时,我要求响应为 arraybuffer 或 blob 类型,以便我可以将其绘制到网页上。我转换它,然后以某种方式绘制它。

   axios.post(Endpoint + 'predict', formData,
            {
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                params: {
                    xmin,
                    ymin,
                    xmax,
                    ymax,
                },
                responseType: 'arraybuffer'
            }).then(response => {
            console.log(response)
            let base64ImageString = Buffer.from(response.data, 'binary').toString('base64')
            let srcValue = "data:image/png;base64,"+base64ImageString
            setImage(srcValue)
            console.log(response.headers)
        })

鉴于请求是针对arraybuffer或blob的,我应该如何访问预测头?

如果我尝试记录 response.headers,我会得到:

{
    "content-type": "image/png"
}

但我无法访问预测标题。

如果需要更多信息,我可以提供。 提前致谢。

编辑 只需在 fastAPI 代码的 CORS 配置中添加 expose_headers 参数即可。参见文档here

【问题讨论】:

    标签: javascript reactjs axios cors fastapi


    【解决方案1】:

    prediction 不是 CORS-safelisted response header,因此它不可用于客户端代码,除非 API 明确授予 Access-Control-Expose-Headers response header 的权限。

    更改 API 以包含:

    Access-Control-Expose-Headers: prediction
    

    在其响应中(在添加 access-control-allow-credentials 的同一段代码中)。

    【讨论】:

    • API 应该已经公开了所有标头。它是用 fastAPI 编写的,代码如下:app.add_middleware( CORSMiddleware, allow_origins=['http://localhost:3000'], allow_credentials=True, allow_methods=["*"], allow_headers=["*"]),当你遇到 fastAPI 的 cors 问题时,通常会建议这样做
    • @juuso — 设置 allow 标头而不是 expose 标头。 Access-Control-Allow-Headers 设置允许客户端发送服务器的标头,而不是允许从响应中读取的标头。
    • 你知道fastAPI怎么做吗?
    • 我想我在这里找到了解决方案。 fastapi.tiangolo.com/tutorial/cors
    猜你喜欢
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 2017-05-09
    • 2021-12-03
    • 1970-01-01
    • 2015-04-05
    相关资源
    最近更新 更多