簡體   English   中英

如何從API響應接收csv類型的文件

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

我有按一下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還是個新手。

原因很簡單, HttpClient嘗試將您的響應解析為JSON,因為這是最常見的情況,也是默認操作。

為了防止HttpClient解析您的響應,您必須在httpOptions中放入responseType: 'text'

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

然后將此對象用作您的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
  });

注意事項

某些服務器可能需要添加一些非標准的Accept標頭,例如:

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

要么

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

或(標准但非語義):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM