content-type header 在 angular 服务调用中缺失

content-type header missing in angular service call

我正在使用 Angular 8Django API。我有一个直接 returns zip 文件的端点。

我用 Postman 测试了端点,一切正常,postman 的响应 header 是

使用相同的负载数据,Angular 没有正确的响应 header

Content-Type 缺失,Content-Length 为 0.

angular 服务是

public download(data: any): Observable<any> {
    const url = `${environment.apiURL}${this.endpoint}download/`;

    return this.http.post(url, data, {responseType: 'blob'});
}

和控制器

private download(payload) {
    this.service.download({data: payload}).subscribe(res => {

      console.log('res: ', res);  // This consoles Blob {size: 0, type: 'text/xml'}

      const b = new Blob([res], {
        type: 'application/zip'
      });
      const url = window.URL.createObjectURL(b);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'qrcodes.zip';
      a.click();

    }, error => {
      console.log('Error downloading multiple files: ', error);
    });
  }

问题是否与后端有关(它在 Postman 中以相同的有效负载工作)或 Angular 中缺少什么?

一旦通过 http headers 尝试使用以下代码,它可能会起作用:

import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'responseType': 'blob',
    // 'Authorization': 'my-auth-token'
  })
};

public multiDownload(data: any): Observable<any> {
    const url = `${environment.apiURL}${this.endpoint}download/`;
    return this.http.post(url, data, httpOptions);
}

最好的处理方法是实施 HTTP 拦截器,它将拦截每个 Web 服务调用并添加 Auth 令牌。

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor( {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            request = request.clone({
                setHeaders: {
                    Authorization: `${auth-token}`
                }
            });
        return next.handle(request);
    }
}

我在使用 angular 8 时遇到了同样的问题,并在此处得到了相同的回复:

谢谢