Angular 2 - Http - 正确忽略空结果 [英] Angular 2 - Http - Properly Ignore Empty Results

查看:20
本文介绍了Angular 2 - Http - 正确忽略空结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多 REST 端点来处理请求并简单地返回 200.我注意到使用 json() 映射结果是一个错误.如果我尝试不进行任何类型的映射,我会看到浏览器警告它无法解析 XML.由于什么都不返回是很常见的,我很好奇我应该如何处理响应.

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();

这是 Firefox 中显示的警告:

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:

如果我尝试使用 json() 进行映射,它会完全崩溃.如果我什么都不做或尝试映射到 text(),我只会收到警告.

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.

在所有情况下,响应头都包含 Content-Length: 0,所以我很惊讶 Angular2/Firefox 试图解析任何东西.我不知道这个警告是来自 Angular2 还是 Firefox.我已经在 Chrome 和 IE 中尝试过这个,但没有警告.所以我想知道它是否特定于 Firefox.

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.

推荐答案

当没有返回内容时,例如return Ok()(HTTP 状态代码 200)在 ASP.NET Core 中,内容类型(自然)未指定,但 Firefox 假定响应为 XML 并尝试解析一个空文档,其中导致以下控制台错误:

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 解析错误:未找到根元素位置...

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

指定 return NoContent();(HTTP 状态代码 204)让 Firefox 高兴(也适用于其他浏览器).

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

该问题已在 Bugzilla@Mozilla 报告:

解析失败只会记录到 Web 控制台.

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

这篇关于Angular 2 - Http - 正确忽略空结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆