如何从API响应接收csv类型的文件

时间:2019-01-18 07:53:26

标签: angular typescript

我有一个导出按钮,可以点击API并以.csv类型发送响应。当我按下API时,响应说status: 200,但我在控制台中收到HttpErrorResponse,并收到此错误

SyntaxError: Unexpected token T in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad

我试图问我的朋友,我必须更改标题,但我不知道如何正确执行此操作。我是否应该将令牌拦截器中的标头设置与设置标头的令牌时的设置相同(如果是,我该怎么做?)?或者我该如何解决我的问题?

这是按钮触发的功能:

onExport = () => {
    this._service.getDataExport(1, 1, this.filter).subscribe(
      res => {
        console.log(res);
        // const filename = `MediaPreparation.csv`;
        // const blob = new Blob([res.data], { type: 'text/csv' });
        // saveAs(blob, filename);
      },
      err => console.log(err)
    );
  }

这是我打的服务:

getDataExport = (page = 1, perPage = 1, filter = null): Observable<any> => {
   const _url = `${this.base_url}/api/v1/media-preparation/export`;

   return this.http.post(_url, {
     page : page.toString(),
     perPage: perPage.toString(),
     filter : filter
   });
}

这是令牌接收器:

import { AuthService } from './auth.service';
import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';

@Injectable()
export class TokenInterceptorService implements HttpInterceptor {

  constructor(private injector: Injector) { }

  intercept(req, next) {
    const authService = this.injector.get(AuthService);
    const tokenizedReq = req.clone({
      setHeaders: {
        Authorization: `Bearer ${authService.getToken()}`
      }
    });

    return next.handle(tokenizedReq);
  }
}

感谢您的帮助,对于错误的解释,我感到很抱歉,我对Angular还是个新手。

1 个答案:

答案 0 :(得分:2)

原因很简单,HttpClient试图将您的响应解析为JSON,因为这是最常见的情况,也是默认操作。

为防止HttpClient解析您的回复,您必须在{em> httpOptions 中放置responseType: 'text'

private httpOptions = {
  headers: new HttpHeaders({}),
  responseType: 'text'
};

然后将此对象用作http方法的最后一个参数(我想得到):

this.http.get(url, httpOptions)
  .subscribe(res => {
    // res is just a string, you have to split it on new lines and commas
    // or you can use a third part library
  });

注意:

如果您的服务器需要它,则可能需要添加一些非标准的Accept标头,例如:

headers: new HttpHeader({
  Accept: 'text/csv'
});

headers: new HttpHeader({
  Accept: 'application/csv'
});

或标准:

headers: new HttpHeader({
  Accept: 'plain/text'
});