Angular请求返回200状态码的API仍报错的问题排查


问题根因
你的报错来自Angular HttpClient方法参数传位错误,叠加前后端响应格式不匹配:
HttpClient.post的参数签名是post(url: string, body: any|null, options?: RequestOptions),你把{ responseType: 'text' }放在了第二个参数(请求体)的位置,配置项根本没传进去,responseType: 'text'的配置完全不生效。- 配置不生效的情况下,HttpClient默认会把所有响应当JSON格式做解析,哪怕后端返回200状态码,只要响应内容不是合法JSON(比如返回空串、纯文本提示、XML结构),解析阶段就会抛出语法错误,请求会进入错误回调,不会执行你subscribe里写的成功逻辑。
- 就算你把responseType放对位置,拿到的响应是纯字符串类型,也不存在
response.success这个属性,现有判断逻辑也无法正常执行。
修复方法
根据你后端的实际返回格式二选一调整即可:
后端返回JSON结构(推荐)
如果你的接口正常返回{success: true, message: "xxx"}这类标准JSON结构,把请求体位置补null,把配置移到第三个参数位置即可,不需要改响应类型:
// service层修正 giveCertificate(studentID:number,certificateID:number):Observable<any>{ // 参数全拼在query里,没有请求体就传null,第三个参数才是配置项 return this.httpClient.post(`https://localhost:6001/Admin/api/Certificates/give?studentID=${studentID}&certificateID=${certificateID}`, null); }
组件层的原有逻辑不需要调整,这时候拿到的response是解析完成的JSON对象,可以正常读取success字段。
后端返回纯文本内容
如果接口本身设计就是返回纯文本提示,把responseType移到正确的配置位,同时调整组件里的响应判断逻辑:
// service层修正 giveCertificate(studentID:number,certificateID:number):Observable<string>{ return this.httpClient.post( `https://localhost:6001/Admin/api/Certificates/give?studentID=${studentID}&certificateID=${certificateID}`, null, { responseType: 'text' } ); } // 组件层修正 giveCertificate(): void { if (this.CertificateAssignmentForm.valid) { const certificateGive = Object.assign(new CertificateGive(), this.CertificateAssignmentForm.value); this.certificateService.giveCertificate(certificateGive.studentID,certificateGive.certificateID) .subscribe(response=>{ // 文本响应直接判断内容即可,不存在success属性 if (response) { this.alertfyService.confirm("Sertifika Öğrenciye Verildi") } }) } }
排查补充:本地调试时确认后端已经配置了对应前端端口的CORS跨域允许规则,否则哪怕接口返回200,浏览器也会拦截响应导致前端报错。
内容的提问来源于stack exchange,提问作者user16421848
相关产品推荐
相关产品推荐

