繁体   English   中英

没有重载匹配此调用。 最后一个重载给出了以下错误。 类型“文本”不能分配给类型“json”

[英]No overload matches this call. The last overload gave the following error. Type '“text”' is not assignable to type '“json”'

I am trying to GET a HTML page from my API using Angular with JWT tokens in the header. 但是如果我没有指定文本类型,编译器会吐出一个无法解析的错误(它会尝试将 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);
        }
);

我是这样做的:

    getDivisionName(x: string): Promise<any> {
    return this.httpClient
      .get<any>(this.serviceUrl + `/something/${x}/`, {
        responseType: 'text' as 'json',
      })
      .toPromise();
  }

暂无
暂无

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

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