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){} }
验证要点
- 确保JSON Server正在运行(通常通过
json-server --watch db.json命令启动),且监听端口为3000。 - 确认请求URL变为
http://localhost:3000/heroes/dc-batman,该地址应返回对应英雄的JSON数据。
内容的提问来源于stack exchange,提问作者Alex Whitney
相关产品推荐
相关产品推荐

