【发布时间】:2021-08-05 11:13:33
【问题描述】:
这是我的前端 React 代码:
import * as React from 'react';
import { useEffect, useState } from 'react';
import http from './http-common'; // axios
type Photo = {
filename: string,
caption: string,
tags: string[].
};
const BrowserArticle = ({ filename, caption, tags }: Photo) => {
const [photoFile, setFile] = useState<string>('');
useEffect(() => {
http.get(`/api/getImg/${filename}`)
.then((response) => {
console.log(typeof response.data); // console output is 'string'
console.log(response); // see screenshot below
setFile(data);
});
}, []);
return (
<div>
<img src={photoFile} alt={filename} />
<div>{caption}</div>
<div>
{
tags.map((tag) => tag)
}
</div>
</div>
);
};
这是我的后端 FastAPI 代码:
from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount('/static', StaticFiles(directory='static'), name='static')
@app.get('/api/getImg/{image_filename}')
async def get_image(image_filename: str) -> FileResponse:
return FileResponse(f'./static/uploads/{image_filename}')
CORS 已得到处理。当我向服务器发送请求时,成功接收到响应,但无法加载图像。经检查,这是生成的 HTML:
当我在then() 函数中console.log(data) 时,这就是我得到的:
当我使用 FastAPI 的内置工具测试 API 时,我验证了 API 成功返回 blob:http://192.168.1.201:8000/0a870a00-cf63-43ef-b952-e49770137fdd
我怀疑是axios收到的数据是图片文件本身,所以我尝试改代码如下:
const [photoFile, setFile] = useState<File | null>(null);
// ...
<img src={photoFile === null ? '' : URL.createObjectURL(photoFile)} alt={filename} />
但是当我刷新页面时,我得到TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.
我尝试搜索如何正确显示从后端接收的图像,但我发现的唯一结果讨论了如何将图像发送到后端或如何显示正在上传到服务器的图像(即显示选择上传的文件的缩略图通过<input type="file" />。与这个特定问题无关。有什么想法吗?
更新:当我执行以下操作时,图像显示成功:
<img src={`http://192.168.1.201:8000/api/getImg/${filename}`} alt={filename} />
但这意味着在生成的 HTML 中公开我的后端,并对后端 IP 进行硬编码。有没有更“正确”的方式来做到这一点?
【问题讨论】:
标签: javascript reactjs typescript jsx fastapi