我的 Angular 2 问题在 AngularJS 中不存在,我将错误消息作为字符串发送给后端 API 调用以防万一我有错误,以错误状态 401 为例,现在的问题是我不能从 Angular2 http 响应消息中读取此消息,而我可以从 AngularJS 中读取此消息:
我尝试了以下代码,但没有任何帮助:
promise :
this._http.post('/login',{email: 'email@example.com', password: '123'})
.toPromise()
.then((resp) => console.log(resp), (error) => console.log(error));
可观察的:
this._http.post('/login',{email: 'email@example.com', password: '123'})
.subscribe(response =>console.log(response), (error) => console.log(error));
然后我从后端发送响应作为文本,对于 OK 或 Unauthorized,对于 OK 我发回 String token == UUID.randomUUID().toString();
,对于错误 I发回类似 String error = "Invalid credentials ";
的消息,问题是 console.log
工作并打印成功文本(在本例中为 token ),但是如果出现错误,它只会打印:Response with status: 200 for URL: null
。
如果我将代码更改为 JSON.stringify(error)
,我会得到如下信息:
{"_body":{},"status":401,"ok":false,"statusText":"Unauthorized","headers":{"null":["HTTP/1.1 401 Unauthorized"],"Access-Control-Allow-Headers":["Origin"," X-Requested-With"," Content-Type"," Accept"," Referer"," User-Agent"],"Access-Control-Allow-Met
hods":["POST"," GET"," PUT"," DELETE"," OPTIONS"],"Access-Control-Allow-Origin":["*"],"Allow":["*"],"Content-Length":["36"],"Content-Type":["text/plain; charset=utf-8"],"Date":["Tue"," 23 Aug 2016 14:53:25 GMT"]},"type":2,"url":null}
如您所见,对象中甚至没有提到错误测试!
我尝试将后端的错误响应更改为返回 json,如下所示:
{
"message": "invalid email or password"
}
我可以在 _body
中得到结果,我只能这样读取它:console.log(error._body.message)
!但我觉得这样不对劲,在这种情况下我不想以 json 的形式响应。
对于 angularjs(angular 1),打印响应非常简单,一切都很酷,而在 angular 2 中,这是一个真正的问题。
问题是什么?如何在不重构后端的情况下解决这个问题?
编辑:
我使用的是 Angular 2.0.0-rc.4,对于 http 也是一样的:`"@angular/http": "2.0.0-rc.4"
最佳答案
莫桑法尔 在我的例子中,我使用 Asp Web Api 作为后端,这件事也让我发疯,我找到的唯一解决方案是在 json 中转换并阅读消息,我知道这真的很丑但对我有用。 问候。
CheckError(error: any) {
let servermsg: any = JSON.parse(error._body)["ModelState"]["Login"][0];
if (servermsg) {
this.showMsg = true;
this.msg = servermsg;
}
}
关于rest - Angular 2如何从后端读取自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39104715/