Angular 2 - Http - Properly Ignore Empty Results

无人久伴 提交于 2019-12-12 14:16:49

问题


I have quite a few REST end-points that process a request and simply return 200. I noticed it is an error to map the result with json(). If I try not to do any sort of mapping whatsoever, I see a browser warning that it could not parse XML. As returning nothing is pretty common, I am curious how I should be handling the response.

Here is a basic code example:

await this.http.put("/api/some_url", data).toPromise();

Here is the warning that shows up in Firefox:

XML Parsing Error: no root element found Location: http://localhost/api/some_url Line Number 1, Column 1:

If I try to map with json(), it blows up entirely. If I do nothing or try to map to text(), I just get the warning.

In all cases, the response headers contain Content-Length: 0, so I am surprised Angular2/Firefox is trying to parse anything. I don't know if this warning is coming from Angular2 or Firefox. I have tried this in Chrome and IE and there is no warning. So I am wondering if it is specific to Firefox.


回答1:


When no content is returned, e.g. return Ok() (HTTP status code 200) in ASP.NET Core, content-type is (naturally) not specified, but Firefox assumes the response to be XML and tries to parse an empty document, which results in the following console error:

XML Parsing Error: no root element found Location ...

Specifying return NoContent(); (HTTP status code 204) makes Firefox happy (and also works for other browsers).

The issue is reported at Bugzilla@Mozilla:

and a parsing failure will simply be logged to the web console instead.



来源:https://stackoverflow.com/questions/45195047/angular-2-http-properly-ignore-empty-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!