【问题标题】:Image not showing from Django rest api in Reactjs图像未从 Reactjs 中的 Django rest api 显示
【发布时间】:2021-08-22 05:21:18
【问题描述】:

我从服务器获得的数据:

[
    {
        "id": 29,
        "name": "atlas",
        "image": "/media/images/images-4.jpeg",
        "price": 67473,
    },
]

在反应中:

//...code
console.log(this.props.img); //>>> /media/images/images-4.jpeg
//...code
<img src={this.props.img} alt='image' width='100%'/>
//...

在 Django 中:

我认为django没有问题。我制作了一个模板并尝试显示图像,它成功了。

那么,如何在 React 中显示图像?

【问题讨论】:

标签: javascript python reactjs django django-rest-framework


【解决方案1】:

Api 仅返回图像的路径。所以在图像链接之前附加基本 url,如下所示

<img src="https://urdomain.com{this.props.img}" alt='image' width='100%'/>

或者在 django 中,您必须发送完整的 url,如下图所示

[
    {
        "id": 29,
        "name": "atlas",
        "image": "https://urdomain.com/media/images/images-4.jpeg",
        "price": 67473,
    },
]

所以不需要附加基本网址

 <img src="{this.props.img}" alt='image' width='100%'/>

【讨论】:

    【解决方案2】:

    您必须将您的域添加到图像路径

    
    const BASE_URL = "your base here" 
    
    <img src={`${BASE_URL}${this.props.img}`} alt='image' width='100%'/>
    
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      • 2021-11-19
      • 2017-04-29
      • 2020-12-12
      相关资源
      最近更新 更多