Angular项目报错TypeError: res.json is not a function 求助
问题解决:Angular中TypeError: res.json is not a function
核心报错原因
从Angular 4.3版本开始,HttpClient会自动解析JSON格式的响应,返回的res已经是解析完成的JavaScript对象,不需要再调用.json()方法,这是报错的直接原因。
代码修正步骤
- 移除错误处理中的
.json()调用 - 删除未被使用的
Success方法 - 修复无限递归问题:原代码中
SuccessGet方法重复调用GetFromServer()会导致无限循环请求,需移除该递归逻辑,改为正常处理数据
修正后的完整代码
GetFromServer(){ this.http.get("http://localhost:3000/Customers") .subscribe({ next: (res) => this.SuccessGet(res), error: (err) => this.Error(err) }); } Error(err: any){ // 直接打印错误信息,或通过err.error查看错误响应体 console.debug(err); } SuccessGet(res: any){ // 将获取到的数据赋值给组件变量,用于UI展示 this.customers = res; console.log('客户数据:', res); }
额外注意事项
- 确保你的模块(如
app.module.ts)已导入HttpClientModule,否则HttpClient无法正常工作:
import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ // ...其他模块 HttpClientModule ] }) export class AppModule { }
- 确认
json-server正在运行(执行json-server --watch db.json命令),且http://localhost:3000/Customers接口能正常返回JSON数据
内容的提问来源于stack exchange,提问作者Vaishali Nimbalkar
相关产品推荐
相关产品推荐

