【问题标题】:API return image path but image is not showing in Angular 10API 返回图像路径,但图像未在 Angular 10 中显示
【发布时间】:2021-08-04 15:23:31
【问题描述】:

我的 API 返回属于产品的图像路径,但我的 Angular 应用程序没有显示图像。

HTML 代码

    <ng-container *ngFor="let prod of productData">
      <div class="row p-2 bg-white border rounded" style="margin-bottom: 10px;">
        <div class="col-md-3 mt-1">
               <img class="img-fluid img-responsive rounded product-image"
               src="{{prod.ProductImages.ImagePath}}"
               [alt]="prod.ProductImages.Name">
        </div>
        <div class="col-md-6 mt-1">
          <h5>{{prod.Name}}</h5>
          <div class="mt-1 mb-1 spec-1">
            |<span> {{prod.Shape.Name}}</span>
            |<span class="dot"></span><span> {{prod.StoneType.Name}}</span>
            |<span class="dot"></span><span> {{prod.Color.Color1}}<br></span>
          </div>
          <div class="mt-1 mb-1 spec-1"><span>{{prod.Supplier.Name}}</span></div>
          </div>
        <div class="align-items-center align-content-center col-md-3 border-left mt-1">
          <div class="d-flex flex-row align-items-center">
            <h4 class="mr-1">{{prod.SellingPrice | currency:'RS: '}}</h4>
          </div>
          <div class="d-flex flex-column mt-4">
            <button class="btn btn-primary btn-sm" type="button" (click)="editProduct(prod.Id)">Details</button>
            <button class="btn btn-outline-primary btn-sm mt-2" type="button">Add to wishlist</button>
          </div>
        </div>
      </div>
    </ng-container> 

跨域读取阻止 (CORB) 阻止了 MIME 类型为 text/html 的跨域响应 https://localhost:44349/。详情请见https://www.chromestatus.com/feature/5629709824032768

如果我像下面这样添加,上面的消息会显示

<img class="img-fluid img-responsive rounded product-image"
           src="https://localhost:44349/{{prod.ProductImages.ImagePath}}"
           [alt]="prod.ProductImages.Name">

【问题讨论】:

  • 如果你在浏览器中打开了路径,你能看到图像工作吗?请把完整的网址也放在这里
  • @WasimNabil 然后它显示一个警告消息我也附上了那个消息
  • 如果您在浏览器 URL 中打开 localhost:44349/Images/Product/6ycFZe.jpg,图像是否有效?没有在应用中加载它
  • @WasimNabil 是的,它正在显示我的图像

标签: angular asp.net-web-api angular10


【解决方案1】:

我解决了这个问题。以下是我解决问题的方法。

    <img class="img-fluid img-responsive rounded product-image"
               [src]="'https://localhost:44349/'+prod.ProductImages[0]?.ImagePath"
               alt="{{prod.Name}}">
          

我使用 [src] 标签而不是 src 标签。

【讨论】:

  • 而且在使用[src]="prod.ProductImages[0]?.ImagePath"时也可以吗?
  • @Pieterjan 我没试过
【解决方案2】:

您只能对某些文件类型发出跨域请求 - 我认为图像是允许的 - 但似乎图像的 MIME 类型在服务器上设置不正确,因此它认为您正在发出跨域请求一个 HTML 文件,这是不允许的 - 如果您拥有服务器,则修复 MIME 类型。

如果没有,那么您将不得不绕过跨域请求 (CORS)。为此,您需要向同一域服务器(或具有允许您进行跨域请求的 CORS 策略的不同域服务器)发出图像的后端请求,然后您的服务器为您获取图像并返回它。这将起作用,因为 CORS 仅由浏览器强制执行。

或者,您可以将 Web 服务器配置为使用 URL 重写/代理。基本上,您从普通域(不受 CORS 限制)请求图像,然后您的网络服务器重写请求并从另一个域获取它。您的浏览器并不聪明,并认为它来自您的域。

【讨论】:

    猜你喜欢
    • 2015-12-11
    • 2023-04-05
    • 2018-12-19
    • 1970-01-01
    • 2012-08-26
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多