【发布时间】:2020-06-20 00:55:55
【问题描述】:
我有一个 ExpressJS 后端端点,它(形象地)是这样的:
function myFunction(req, res, next) {
if (someErrorCondition)
res.status(400).json({message: "Something went wrong."});
else {
myBackendService.someFunc.then(res.status(200).json({message: "Success!"}))
.catch(err => next(err))
}
}
从一个 Angular 前端组件,我通过订阅请求这个端点:
this.myFrontendService.someFunc().subscribe(
res => {
console.log(res);
},
error => {
console.log(error);
});
当调用正确运行时(即状态 200),将 JSON 对象 {message: "Success!"} 记录(如预期)为 res 对象。但是当它失败时,它会记录:
Http failure response for http://localhost:4000/myRoute/myFunction: 400 Bad Request
而且我在任何地方都没有收到“出现问题”的消息。我从后端发送的。错误代码在 Angular 中的处理方式是否不同?
此外,当我使用 cURL 调用后端端点时,两条消息都按预期作为 JSON 对象返回。
编辑:myFrontService 类声明如下所示:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class FrontendService {
constructor(private http: HttpClient) { }
someFunc() {
return this.http.put(`localhost:4000/myRoute/myFunction`, {data: "here's some data"});
}
}
【问题讨论】:
-
this.myFrontendService.someFunc() 是什么样的?
-
@E.Maggini 我编辑了问题:)
标签: angular http error-handling