【问题标题】:No overload matches this call. The last overload gave the following error. Type '"text"' is not assignable to type '"json"'没有重载匹配此调用。最后一个重载给出了以下错误。类型 '"text"' 不可分配给类型 '"json"'
【发布时间】:2020-03-14 19:00:21
【问题描述】:

我正在尝试使用带有 JWT 令牌的 Angular 从我的 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>

【问题讨论】:

  • 内容类型标头是否正确?通过 POSTMAN 之类的客户端访问此 API 时,您传递了哪些标头?
  • @NicholasK in Postman 我只指定 Authorization 标头与格式为 Bearer 的令牌
  • httpCilentModule 默认会解析您的请求,因此您必须指定内容类型
  • 另外,为什么要在 GET 请求中指定 Content-Type?仅适用于 PUT、PATCH、POST(实际在其正文中发送数据的请求)的 AFAIK。
  • 根据您之前的评论,无需将Content-Type 作为标题传入。

标签: javascript angular xmlhttprequest jwt angular-httpclient


【解决方案1】:

您可以在您的组件中尝试以下操作,以查看您的呼叫是否适用于其他网站。以下内容应将请求页面的 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);
        }
);

【讨论】:

  • 这可以作为评论而不是答案吗?
  • No overload matches this call. :/
  • 我已经更新了我的答案,以防止 @Munchkin 出现“不超载”消息。我已经在一个示例项目中尝试过这个解决方案,它会在控制台中返回请求的 url 的 HTML。
  • @NicholasK 我已经发布了这个答案,因为它是上述问题的解决方案,并且是一种从 url 检索 HTML 的方法,例如他的 API。
  • 这确实有效!现在如何添加 JWT Token 以及如何让检索到的内容刷新视图?
【解决方案2】:

我是这样做的:

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

【讨论】:

猜你喜欢
  • 2020-01-03
  • 2023-03-28
  • 2021-06-05
  • 1970-01-01
  • 2019-12-21
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多