Angular HttpClient“解析期间的Http失败" [英] Angular HttpClient "Http failure during parsing"

查看:185
本文介绍了Angular HttpClient“解析期间的Http失败"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从Angular 4向我的Laravel后端发送POST请求.

I try to send an POST request from Angular 4 to my Laravel backend.

我的LoginService具有以下方法:

My LoginService has this method:

login(email: string, password: string) {
    return this.http.post(`http://10.0.1.19/login`, { email, password })
}

我在LoginComponent中订阅了此方法:

I subscribe to this method in my LoginComponent:

.subscribe(
    (response: any) => {
        console.log(response)
        location.reload()
    }, 
    (error: any) => {
        console.log(error)
    })

这是我的Laravel后端方法:

And this is my Laravel backend method:

...

if($this->auth->attempt(['email' => $email, 'password' => $password], true)) {
  return response('Success', 200);
}

return response('Unauthorized', 401);

我的Chrome开发人员工具说我的请求成功,并带有200个状态代码.但是我的Angular代码触发了error块并给出了以下消息:

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://10.0.1.19/api/login 期间的Http失败

Http failure during parsing for http://10.0.1.19/api/login

如果我从后端返回一个空数组,则可以正常工作...所以Angular试图将我的响应解析为JSON?我该如何禁用它?

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?

推荐答案

您可以使用responseType指定要返回的数据为 not JSON.

You can specify that the data to be returned is not JSON using responseType.

在您的示例中,您可以使用responseType字符串值text,如下所示:

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'})

responseType的选项的完整列表为:

The full list of options for responseType is:

  • json(默认)
  • text
  • arraybuffer
  • blob
  • json (the default)
  • text
  • arraybuffer
  • blob

有关更多信息,请参见文档.

See the docs for more information.

这篇关于Angular HttpClient“解析期间的Http失败"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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