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

查看:122
本文介绍了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.

推荐答案

当没有返回任何内容时,例如在ASP.NET Core中返回Ok()(HTTP状态代码200),内容类型(自然)未指定,但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 ...

指定返回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天全站免登陆