node.js - 如何在 react 中显示base64图像?

标签 node.js reactjs mongodb base64

我将图像以 base64 格式存储在 Node 中。然后我收到它并存储在一个变量中。并将其显示在标签中,但未显示。正在从服务器接收正确的值。在渲染中,如果状态已设置,则函数条件为真。即使它为真,也不会显示。

getImage() {
    console.log('getImage');
    axios.get(`http://localhost:4000/image/get`).then((result) => {
        this.setState({ image: result })
        console.log(result);
    });
}

render(){
    {this.state.image ? <img src={this.state.image}></img>: ''}
}

我得到存储在服务器中的精确 base64 字符串。它返回

<img src="[object Object]">

在 DOM 中。我不知道我哪里出错了

编辑

router.route('/image/get').get((req, res) => {
    console.log('inside img get');
    Image.find((err, result) => {
        if (err) {
            res.json({ "error": true, "message": "error fetching data" });
        } else {
            // console.log(result);
            res.json(result);
        }
    })

});

模型

const mongoose=require('mongoose');
const Schema=mongoose.Schema;
var ImageSchema=new Schema({
    imageName:{
        type:String
    },
    imageData:{
        type:String
    }

});

export default mongoose.model('Image', ImageSchema);

最佳答案

您确定在 src 属性中添加编码类型以及 base64 编码值吗?

render(){
    {this.state.image ? <img src={`data:image/png;base64,${this.state.image}`}/>: ''}
}

关于node.js - 如何在 react 中显示base64图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56769076/

相关文章:

javascript - 根据类别更新对象类型的mongodb字段

javascript - 异步方法链?

reactjs - TypeScript 打字问题(与 (P)React 略有相关)

java - MongoDB - Morphia 嵌入式

java - 从JSONObject获取日期

spring - Mongo 说坐标越界

node.js - sails.js 服务中的水线错误实现

javascript - 我应该在 Node.js 和 Express 中链接方法和函数吗?

javascript - "Import in body of module; reorder to top import/first"跨多个文件

javascript - react : Trying to set an API JSON response to state object and pass it to component for mapping and rendering