作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有导出按钮,它点击 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);
}
}
最佳答案
原因很简单,HttpClient
正在尝试将您的响应解析为 JSON,因为这是最常见的场景和默认操作。
防止HttpClient
要解析您的回复,您必须输入 responseType: 'text'
在您的 httpOptions 中:
private httpOptions = {
headers: new HttpHeaders({}),
responseType: 'text'
};
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'
});
关于angular - 如何从 API 响应接收类型为 csv 的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54249721/
我是一名优秀的程序员,十分优秀!