【问题标题】:Angular2 XHR Request error handling : unable to get real bodyAngular2 XHR 请求错误处理:无法获取实体
【发布时间】:2017-05-20 01:20:22
【问题描述】:

我很难理解在 http 调用出现错误时的行为。

目标是根据服务器在 403 或 400 响应时返回的错误消息有不同的行为。

使用 Chrome 网络时,我可以看到消息

但是,当我对错误进行 console.log 时,我得到的只是正文中的 ProgressEvent 对象。

有问题的代码非常简单,200 处理得很好,返回的 json 是可访问的。

this.service.myFunction(this.email).subscribe(
        auth => console.log(auth), // works fine
        error => console.log(error) 
    );

在实际调用中,我也尝试了 catch,但没有成功。

this.myFunction.get(url).map(res => res.json())
    .catch( (err: Response) => Observable.throw(err.json()) ); //     throw the error, which is also the object described above

你知道我做错了什么吗?

谢谢

【问题讨论】:

    标签: angular xmlhttprequest


    【解决方案1】:

    试试这个:

    this.service.myFunction(this.email).subscribe(
        auth => console.log(auth), // works fine
        error => console.log(error.text()) 
    );
    

    Response 的 Angular 2 文档说:

    Response 的接口受 Fetch Spec 中定义的 Response 构造函数的启发,但被认为是一个静态值,其主体可以被多次访问。实现中还有其他差异,但这是最重要的。

    因此,如果.text() 不再发送完整的响应正文,您将不得不更改您的服务器实现以发送 200 OK 和您的错误消息。

    我猜问题是 XMLHTTPRequest 的状态通过读取标头而改变,然后 Angular 的 Http 库停止读取正文... (Read this)

    【讨论】:

    • 感谢您的回答我怀疑是这样的。使用 .text() 我得到 { "isTrusted": true } 所以我怀疑这还不够:) 最好的解决方案是 200 有办法知道这是一个错误吗?
    • 我有时会看到 API 产品只有 200 OK 和一个带有状态和消息的 Json Response 对象。就我而言,它适用于错误状态代码和错误消息,但我看不出与您的区别......请注意,根据服务器实现,您可以有不同类型的正文响应。 Angular 2 支持body: string|Object|ArrayBuffer|Blob;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    相关资源
    最近更新 更多