Angular HttpClient“解析时Http失败" [英] Angular HttpClient "Http failure during parsing"
问题描述
我尝试从 Angular 4 向我的 Laravel 后端发送 POST 请求.
我的 LoginService 有这个方法:
登录(电子邮件:字符串,密码:字符串){return this.http.post(`http://10.0.1.19/login`, { email, password })}
我在我的 LoginComponent 中订阅了这个方法:
.subscribe((回复:任何)=>{控制台日志(响应)location.reload()},(错误:任何)=>{控制台日志(错误)})
这是我的 Laravel 后端方法:
<预><代码>...if($this->auth->attempt(['email' => $email, 'password' => $password], true)) {return response('成功', 200);}return response('未授权', 401);我的 Chrome 开发工具显示我的请求成功,状态码为 200.但是我的 Angular 代码触发了 error
块并给了我这个消息:
如果我从后端返回一个空数组,它就可以工作……所以 Angular 试图将我的响应解析为 JSON?如何禁用此功能?
您可以使用 responseType
指定要返回的数据不是 JSON.
在您的示例中,您可以使用 text
的 responseType
字符串值,如下所示:
返回 this.http.post('http://10.0.1.19/login',{电子邮件,密码},{响应类型:'文本'})
responseType
的完整选项列表是:
json
(默认)text
arraybuffer
blob
有关详细信息,请参阅文档.
I try to send an POST request from Angular 4 to my Laravel backend.
My LoginService has this method:
login(email: string, password: string) {
return this.http.post(`http://10.0.1.19/login`, { email, password })
}
I subscribe to this method in my LoginComponent:
.subscribe(
(response: any) => {
console.log(response)
location.reload()
},
(error: any) => {
console.log(error)
})
And this is my Laravel backend method:
...
if($this->auth->attempt(['email' => $email, 'password' => $password], true)) {
return response('Success', 200);
}
return response('Unauthorized', 401);
My Chrome dev tools says that my request was a success with 200 status code. But my Angular code triggers the error
block and gives me this message:
Http failure during parsing for http://10.0.1.19/api/login
If I return an empty array from my backend, it works... So Angular is trying to parse my response as JSON? How can i disable this?
You can specify that the data to be returned is not JSON using responseType
.
In your example, you can use a responseType
string value of text
, like this:
return this.http.post(
'http://10.0.1.19/login',
{email, password},
{responseType: 'text'})
The full list of options for responseType
is:
json
(the default)text
arraybuffer
blob
See the docs for more information.
这篇关于Angular HttpClient“解析时Http失败"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!