我正在尝试将一个随机生成的图像从 Flask API 发送到我的 React 前端。我开始时每次将图像生成到文件系统时都将其保存,然后尝试使用 react 访问它,但这不适用于生产版本。现在我正在使用 Flask 的 send_file(),但我不确定我在前端做错了什么,因为这是我的第一个 React 项目。
在烧瓶中我有:
@main.route('/get-image', methods=['GET'])
def get_image():
image_array = generate_random_image()
img = Image.fromarray(image_array)
img.save('img.png')
return send_file('img.png', 'image/png')
Run Code Online (Sandbox Code Playgroud)
并在前端
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
image: '/get-image'
};
}
updateImage() {
fetch("/get-image").then(response => {
this.setState({image: /** not sure what to have here **/});
})
}
render() {
return (
<div className="App">
<Container>
<Row>
<Col>
<Image src={this.state.image} rounded/>
</Col>
</Row>
<Row>
<Container>
<Container>
<Row>
<Col>
<Button …Run Code Online (Sandbox Code Playgroud)