Angular HttpClient "Http failure during parsing"

nutzt picture nutzt · Sep 25, 2017 · Viewed 158.2k times · Source

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?

Answer

Kirk Larkin picture Kirk Larkin · Sep 25, 2017

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.