首页 文章

Angular 4 http在没有正文的PUT响应中抛出错误

提问于
浏览
1

我正在使用Angular http模块v4.4.6 . 当Angular应用程序(客户端)正在向服务器发送PUT请求(使用 HttpClient ),并且服务器响应状态200(OK)而主体中没有任何数据时,角度http模块将抛出 HttpErrorResponse .

这是一个正确的功能还是一个错误?
如何在没有任何数据的情况下处理PUT响应?


详细地:

在最近的版本中,我使用了普通的 Http 模块,它的方法是put() . 在那里,我需要调用 res.json() 来获取正文中的JSON数据 . put()方法返回 Observable<Response> .

现在我使用更新的 HttpClient 和它的put()方法 . 此方法返回 Observable<Object> . 似乎内部调用 json() 方法并导致我看到的错误 .

  • Angular客户端使用HttpHeader 'Content-Type': 'application/json' 创建PUT请求 . 这导致HTTP PUT请求头 Accept:application/json, text/plain, */* ) .

  • 服务器以状态200(OK)回答,并且正文中没有任何数据 .

  • Angular客户端收到答案并抛出错误 .

HttpErrorResponse {headers: HttpHeaders, status: 200, ... error: error: SyntaxError: Unexpected end of JSON input at .. text: "" headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: ... message: "Http failure during parsing for ... name: "HttpErrorResponse" ok: false status: 200 statusText: "OK" url: ...

1 回答

  • 5

    @yonexbat,谢谢你是对的 .

    如果使用....

    const response = this.http.put(url, data, { responseType: 'text'}).toPromise();
    

    ... 问题已经解决了 .

相关问题