【问题标题】:Angular - Sample Down failed to load response dataAngular - Sample Down 无法加载响应数据
【发布时间】:2021-08-12 00:53:57
【问题描述】:

在我的 Angular-12 中,我尝试在 Excel 导入之前加载示例下载,以便用户查看下载的模式应该如何:

服务:

downloadSample(): any {
  return this.http.get('http://localhost:8080/sample_download/countries.xlsx', {responseType: 'blob'});
}

组件:

downloadSample() {
  this.countriesService.downloadSample().subscribe((response: any) => { //when you use stricter type checking
    let blob:any = new Blob([response], { type: 'text/json; charset=utf-8' });
    const url = window.URL.createObjectURL(blob);
    fileSaver.saveAs(blob, 'countries.json');
    Swal.fire({
      position: 'center',
      icon: 'success',
      title: 'Sample File downloaded successfully',
      showConfirmButton: true,
      timer: 5000
    });
  }),
  Swal.fire({
    position: 'center',
    icon: 'error',
    title: 'Sample File downloaded Failed',
    showConfirmButton: true,
    timer: 5000
  });
}

HTML:

<h5> Download the sample format of Excel sheet. <input type="button" (click)="downloadSample()" value="Download Excel Template"/></h5>

我收到了这个错误:

从源访问 'http://localhost:8080/sample_download/countries.xlsx' 的 XMLHttpRequest “http://localhost:4200”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

“http://localhost:8080/sample_download/countries.xlsx 的 Http 失败响应:0 未知错误” 消息:“未知错误”

我该如何解决这些问题?

谢谢

【问题讨论】:

标签: angular


【解决方案1】:

可以通过将前端端口列入白名单从后端进行修复,最有可能是 4200。

【讨论】:

  • 很可能是这样的:对于 django,在设置文件中,应该添加 CORS_ALLOW_WHITELIST = (portnumber1, portnumber2)。
猜你喜欢
  • 1970-01-01
  • 2015-12-25
  • 1970-01-01
  • 2018-06-15
  • 2018-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多