简体   繁体   English

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

[英]How to receive file with type csv from API response

I have the export button which hit API and send response in .csv type. 我有按一下API并以.csv类型发送响应的导出按钮。 When i hit the API, the response said status: 200 but i getting HttpErrorResponse in the console, and got this error 当我点击API时,响应表示status: 200但是我在控制台中收到HttpErrorResponse ,并收到此错误

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

I have tried to ask my friend that I have to change my Header, but i don't understand how to do it properly. 我试图问我的朋友,我必须更改标题,但我不知道如何正确执行此操作。 Should i set the header within Token Interceptor as same as when i set the token of the headers (if ya, how can I do that?)? 我是否应该将令牌拦截器中的标头设置与设置标头的令牌时的设置相同(如果是,我该怎么做?)? Or how can i solve my problem? 或者我该如何解决我的问题?

This is the function that the button triggered: 这是按钮触发的功能:

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)
    );
  }

This this is the service that I hit: 这是我击中的服务:

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
   });
}

and this is the Token Inteceptor: 这是令牌接收器:

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);
  }
}

Thanks for helping, and I am sorry for the bad explanation, I stil beginner in Angular. 感谢您的帮助,对于不好的解释,我深感抱歉,我对Angular还是个新手。

The reason is easy, HttpClient is trying to parse your response as JSON, since it's the most common scenario and the default action. 原因很简单, HttpClient尝试将您的响应解析为JSON,因为这是最常见的情况,也是默认操作。

To prevent HttpClient to parse your response, you have to put responseType: 'text' in your httpOptions : 为了防止HttpClient解析您的响应,您必须在httpOptions中放入responseType: 'text'

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

Then use this object as last parameter of your http method (I suppose get): 然后将此对象用作您的http方法的最后一个参数(我想得到get):

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
  });

Note : 注意事项

Some servers may need to add some not-standard Accept header, for example: 某些服务器可能需要添加一些非标准的Accept标头,例如:

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

Or 要么

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

Or (standard but not semantic): 或(标准但非语义):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM