我正在尝试使用Angular在标题中使用JWT令牌从我的API中获取HTML页面。但是,如果我不指定文本类型,则编译器会发出无法解析的错误(然后它将尝试将HTML解析为JSON),因此我需要指定响应类型。
这是我的component.ts:
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer TOKENHERE'
})
};
constructor(private http: HttpClient) { }
ngOnInit() {
}
fetchDashboard() {
this.http.get('http://localhost:3000/avior/dashboard', {responseType: 'text', this.httpOptions,}).subscribe(j => console.log(j));
}
}
我尝试将内容类型删除或更改为text / html,但无济于事。
我的API响应:
<html><head><title>Dashboard</title></head><body><h1>Dashboard works!</h1></body></html>
您可以在组件中尝试以下操作,以查看您的呼叫是否可以访问其他网站。以下内容应以字符串形式返回请求页面的html。如果这不适用于您的API,则问题可能不在于组件中的代码,而是您的API返回的响应
const requestOptions: Object = {
headers: new HttpHeaders().append('Authorization', 'Bearer <yourtokenhere>'),
responseType: 'text'
}
this.http.get<string>('https://cors-anywhere.herokuapp.com/https://stackoverflow.com/questions/tagged/angular',
requestOptions)
.subscribe(response => {
console.log(response);
}
);