gpt4 book ai didi

node.js - 如何在 Angular 应用程序中显示 Node js api 错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:59 26 4
gpt4 key购买 nike

在我的 Node.js 应用程序中,我返回如下错误:

app.get('/api/login', (req, res, next) => {
//...
return res.status(400).send({
isSuccess: false,
errors: ["error 1", "error 2"]
})
})

在 Angular 中,如何得到错误?

login() {
const headers = new HttpHeaders().set('Accept', 'application/json').set('Content-Type', 'application/json');
this.http.post('http://localhost:3000/api/login', { username: 'arwels', password: '24899632' }, { headers: headers }).subscribe(response => {
// ok
}, (err) => {
console.log(err) // Bad Reqeust
});
}

当我在错误部分打印 err 时,它会打印 Bad Reqeust。服务器发送的对象在哪里?

最佳答案

您可以使用 HttpInterceptor 捕获来自 API 的错误响应。

引用号:https://angular.io/api/common/http/HttpInterceptor

这是一个例子:

export class MyHttpInterceptor implements HttpInterceptor {
constructor() {
}
intercept( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(async (_err: HttpErrorResponse, _caught: any) => {
switch (_err.status) {
case 401:
...
break;
case 500:
...
break;
default:
...
break;
}
return of(_err);
})
) as any;
}
}

由于您可以完全控制 API 中返回错误的方式,因此您可以定制 HttpInterceptor 以处理您想要在后端创建的任何错误对象。

不利的选择

如果您只想要完整的响应,以便可以嗅出 statusCode,您也可以在 HttpHeaders 中{observe: 'response'}

this.http.get<HttpResponse<any>>(<url>, {observe: 'response'}).pipe(
tap(resp => console.log('response', resp))
);

关于node.js - 如何在 Angular 应用程序中显示 Node js api 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60031101/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com