You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular GET请求遇HttpErrorResponse解析失败问题求助

问题分析与解决方案

核心问题

你的GET请求发送到了Angular开发服务器(http://localhost:4200/dc-batman),而非JSON Server的API地址(http://localhost:3000/heroes/dc-batman),因此返回的是Angular应用的HTML页面,而非预期的JSON数据,导致解析失败。

错误原因

在HeroesService的getInfoId方法中,你直接将id作为请求URL传入,未拼接JSON Server的基础地址urlHeroes。Angular会将相对路径(如dc-batman)解析为当前应用服务器的地址,而非JSON Server的地址。

修复步骤

修改HeroesService中的getInfoId方法,将基础地址与id拼接生成正确的API请求URL:

@Injectable()
export class HeroesService{

    urlHeroes: string = "http://localhost:3000/heroes";

    getInfoId(id:string): Observable<SearchHeroesResponse>{
        // 拼接基础地址和id,指向JSON Server的正确接口
        return this.http.get<SearchHeroesResponse>(`${this.urlHeroes}/${id}`);
    }

    constructor(private http:HttpClient){}
}

验证要点

  1. 确保JSON Server正在运行(通常通过json-server --watch db.json命令启动),且监听端口为3000。
  2. 确认请求URL变为http://localhost:3000/heroes/dc-batman,该地址应返回对应英雄的JSON数据。

内容的提问来源于stack exchange,提问作者Alex Whitney

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 23:26:07