Angular HttpClient "Http failure during parsing"
Angular HttpClient "Http failure during parsing"
我尝试从 Angular 4 向我的 Laravel 后端发送 POST 请求。
我的登录服务有这个方法:
login(email: string, password: string) {
return this.http.post(`http://10.0.1.19/login`, { email, password })
}
我在我的 LoginComponent 中订阅了这个方法:
.subscribe(
(response: any) => {
console.log(response)
location.reload()
},
(error: any) => {
console.log(error)
})
这是我的 Laravel 后端方法:
...
if($this->auth->attempt(['email' => $email, 'password' => $password], true)) {
return response('Success', 200);
}
return response('Unauthorized', 401);
我的 Chrome 开发工具说我的请求成功,状态代码为 200。但是我的 Angular 代码触发了 error
块并给我这条消息:
Http failure during parsing for http://10.0.1.19/api/login
如果我 return 来自后端的一个空数组,它可以工作...所以 Angular 正在尝试将我的响应解析为 JSON?我怎样才能禁用它?
可以使用responseType
.
指定返回的数据是不是JSON
在您的示例中,您可以使用 text
的 responseType
字符串值,如下所示:
return this.http.post(
'http://10.0.1.19/login',
{email, password},
{responseType: 'text'})
responseType
的完整选项列表是:
json
(默认值)
text
arraybuffer
blob
有关详细信息,请参阅 docs。
如果你有选择
return this.http.post(`${this.endpoint}/account/login`,payload, { ...options, responseType: 'text' })
即使加上responseType,我也处理了好几天都没有成功。
终于我明白了。
确保在后端脚本中没有将 header 定义为 -("Content-Type: application/json);
因为如果你把它变成文本但后端要求 json,它会 return 一个错误...
我在 Angular 申请中遇到了同样的问题。我在我的应用程序中使用了 RocketChat REST API,我试图使用 rooms.createDiscussion
,但出现如下错误。
ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"myurl/rocketchat/api/v1/rooms.createDiscussion","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for myrul/rocketchat/api/v1/rooms.createDiscussion","error":{"error":{},"text":"
我尝试了一些方法,例如更改 responseType: 'text'
,但其中 none 有效。最后我发现问题出在我的 RocketChat 安装上。正如在 RocketChat change log 中提到的 API rooms.createDiscussion
是在版本 1.0.0 中引入的,不幸的是我使用的是较低版本。
我的建议是在花时间修复 Angular 代码中的错误之前检查 REST API 是否正常工作。我使用 curl
命令来检查。
curl -H "X-Auth-Token: token" -H "X-User-Id: userid" -H "Content-Type: application/json" myurl/rocketchat/api/v1/rooms.createDiscussion -d '{ "prid": "GENERAL", "t_name": "Discussion Name"}'
我也收到了无效的 HTML 作为响应。
<!DOCTYPE html>
<html>
<head>
<meta name="referrer" content="origin-when-crossorigin">
<script>/* eslint-disable */
'use strict';
(function() {
var debounce = function debounce(func, wait, immediate) {
而不是如下所示的有效 JSON 响应。
{
"discussion": {
"rid": "cgk88DHLHexwMaFWh",
"name": "WJNEAM7W45wRYitHo",
"fname": "Discussion Name",
"t": "p",
"msgs": 0,
"usersCount": 0,
"u": {
"_id": "rocketchat.internal.admin.test",
"username": "rocketchat.internal.admin.test"
},
"topic": "general",
"prid": "GENERAL",
"ts": "2019-04-03T01:35:32.271Z",
"ro": false,
"sysMes": true,
"default": false,
"_updatedAt": "2019-04-03T01:35:32.280Z",
"_id": "cgk88DHLHexwMaFWh"
},
"success": true
}
所以在 更新到最新的 RocketChat 之后,我能够使用提到的 REST API。
您还应该检查一下 JSON(不是在 DevTools 中,而是在后端)。 Angular HttpClient 很难用 [=10=]
个字符解析 JSON,然后 DevTools 将忽略,因此很难在 Chrome.
中发现
我遇到了同样的问题,原因是
在后端 returning 字符串 (spring) 时,您可能 returning 作为
return "spring used";
但是根据spring,这没有被正确解析。
而是使用 return "\" spring 使用 \"";
- 和平
我将 .NetCore 用于我的后端任务,我能够通过使用 Newtonsoft.Json 库包到 return 来自我的控制器的 JSON 字符串来解决这个问题。
显然,并非所有 JSON 序列化器都是按照正确的规范构建的..NET 5 的“return Ok("");”绝对不够。
在我的例子中,问题是 url 调用中缺少“/”,就在资源之后。然后它试图获取 angular 组件 (html) 而不是 JSON 资源。我希望这会有所帮助,因为我没有在此线程中找到我的问题的答案。
我只想补充一点,您必须在 get/post 方法 (.get<T>
) 上 省略通用参数 。
✔️ 这会起作用:
this.http.get(`https://myapi.com/health`, {responseType: 'text'})
❌ 这 不会 工作:
this.http.get<string>(`https://myapi.com/health`, {responseType: 'text'})
后面会报错:
The expected type comes from property 'responseType' which is declared
here on type '{ headers?: HttpHeaders | { [header: string]: string |
string[]; } | undefined; observe: "events"; context?: HttpContext |
undefined; params?: HttpParams | { ...; } | undefined;
reportProgress?: boolean | undefined; responseType?: "json" |
undefined; withCredentials?: boolean | undefined; }'
我遇到了同样的问题,但就我而言,我忘记将代理 url 添加到 api。
readonly apiUrl = this.appConfigService.appConfig.apiUrl + 'EndPointUrl';
这个答案帮助我弄明白了:
就我而言,我在 PHP 结果中换行。
例如,
echo json_encode($row)."\<br/>";
我删除了 <br/>
,一切正常。
我尝试从 Angular 4 向我的 Laravel 后端发送 POST 请求。
我的登录服务有这个方法:
login(email: string, password: string) {
return this.http.post(`http://10.0.1.19/login`, { email, password })
}
我在我的 LoginComponent 中订阅了这个方法:
.subscribe(
(response: any) => {
console.log(response)
location.reload()
},
(error: any) => {
console.log(error)
})
这是我的 Laravel 后端方法:
...
if($this->auth->attempt(['email' => $email, 'password' => $password], true)) {
return response('Success', 200);
}
return response('Unauthorized', 401);
我的 Chrome 开发工具说我的请求成功,状态代码为 200。但是我的 Angular 代码触发了 error
块并给我这条消息:
Http failure during parsing for http://10.0.1.19/api/login
如果我 return 来自后端的一个空数组,它可以工作...所以 Angular 正在尝试将我的响应解析为 JSON?我怎样才能禁用它?
可以使用responseType
.
在您的示例中,您可以使用 text
的 responseType
字符串值,如下所示:
return this.http.post(
'http://10.0.1.19/login',
{email, password},
{responseType: 'text'})
responseType
的完整选项列表是:
json
(默认值)text
arraybuffer
blob
有关详细信息,请参阅 docs。
如果你有选择
return this.http.post(`${this.endpoint}/account/login`,payload, { ...options, responseType: 'text' })
即使加上responseType,我也处理了好几天都没有成功。 终于我明白了。 确保在后端脚本中没有将 header 定义为 -("Content-Type: application/json);
因为如果你把它变成文本但后端要求 json,它会 return 一个错误...
我在 Angular 申请中遇到了同样的问题。我在我的应用程序中使用了 RocketChat REST API,我试图使用 rooms.createDiscussion
,但出现如下错误。
ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"myurl/rocketchat/api/v1/rooms.createDiscussion","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for myrul/rocketchat/api/v1/rooms.createDiscussion","error":{"error":{},"text":"
我尝试了一些方法,例如更改 responseType: 'text'
,但其中 none 有效。最后我发现问题出在我的 RocketChat 安装上。正如在 RocketChat change log 中提到的 API rooms.createDiscussion
是在版本 1.0.0 中引入的,不幸的是我使用的是较低版本。
我的建议是在花时间修复 Angular 代码中的错误之前检查 REST API 是否正常工作。我使用 curl
命令来检查。
curl -H "X-Auth-Token: token" -H "X-User-Id: userid" -H "Content-Type: application/json" myurl/rocketchat/api/v1/rooms.createDiscussion -d '{ "prid": "GENERAL", "t_name": "Discussion Name"}'
我也收到了无效的 HTML 作为响应。
<!DOCTYPE html>
<html>
<head>
<meta name="referrer" content="origin-when-crossorigin">
<script>/* eslint-disable */
'use strict';
(function() {
var debounce = function debounce(func, wait, immediate) {
而不是如下所示的有效 JSON 响应。
{
"discussion": {
"rid": "cgk88DHLHexwMaFWh",
"name": "WJNEAM7W45wRYitHo",
"fname": "Discussion Name",
"t": "p",
"msgs": 0,
"usersCount": 0,
"u": {
"_id": "rocketchat.internal.admin.test",
"username": "rocketchat.internal.admin.test"
},
"topic": "general",
"prid": "GENERAL",
"ts": "2019-04-03T01:35:32.271Z",
"ro": false,
"sysMes": true,
"default": false,
"_updatedAt": "2019-04-03T01:35:32.280Z",
"_id": "cgk88DHLHexwMaFWh"
},
"success": true
}
所以在 更新到最新的 RocketChat 之后,我能够使用提到的 REST API。
您还应该检查一下 JSON(不是在 DevTools 中,而是在后端)。 Angular HttpClient 很难用 [=10=]
个字符解析 JSON,然后 DevTools 将忽略,因此很难在 Chrome.
我遇到了同样的问题,原因是 在后端 returning 字符串 (spring) 时,您可能 returning 作为 return "spring used"; 但是根据spring,这没有被正确解析。 而是使用 return "\" spring 使用 \""; - 和平
我将 .NetCore 用于我的后端任务,我能够通过使用 Newtonsoft.Json 库包到 return 来自我的控制器的 JSON 字符串来解决这个问题。
显然,并非所有 JSON 序列化器都是按照正确的规范构建的..NET 5 的“return Ok("");”绝对不够。
在我的例子中,问题是 url 调用中缺少“/”,就在资源之后。然后它试图获取 angular 组件 (html) 而不是 JSON 资源。我希望这会有所帮助,因为我没有在此线程中找到我的问题的答案。
我只想补充一点,您必须在 get/post 方法 (.get<T>
) 上 省略通用参数 。
✔️ 这会起作用:
this.http.get(`https://myapi.com/health`, {responseType: 'text'})
❌ 这 不会 工作:
this.http.get<string>(`https://myapi.com/health`, {responseType: 'text'})
后面会报错:
The expected type comes from property 'responseType' which is declared here on type '{ headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; observe: "events"; context?: HttpContext | undefined; params?: HttpParams | { ...; } | undefined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }'
我遇到了同样的问题,但就我而言,我忘记将代理 url 添加到 api。
readonly apiUrl = this.appConfigService.appConfig.apiUrl + 'EndPointUrl';
这个答案帮助我弄明白了:
就我而言,我在 PHP 结果中换行。
例如,
echo json_encode($row)."\<br/>";
我删除了 <br/>
,一切正常。