Angular HttpClient "Http failure during parsing"
Asked Answered
M

13

209

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?

Myrticemyrtie answered 25/9, 2017 at 15:8 Comment(0)
R
424

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:

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.

Reminiscent answered 25/9, 2017 at 15:12 Comment(2)
The same solution is not working for me. I dont want to oepn a new question as mine is almost the same question. Whats wrong here : return this.http.post<any>(this._addToUpvotersListURL, { responseType: 'text' });Akin
@Akin Please see my answer: https://mcmap.net/q/126300/-angular-httpclient-quot-http-failure-during-parsing-quotReincarnate
R
84

I just want to add that you have to omit the generic argument on the get/post method method (.get<T>).

✔️ This will work:

this.http.get(`https://myapi.com/health`, {responseType: 'text'})

❌ This will not work:

this.http.get<string>(`https://myapi.com/health`, {responseType: 'text'})

The later will produce an error:

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

Reincarnate answered 15/10, 2021 at 9:20 Comment(4)
Yes this works, but why?Redfaced
@FatihErsoy because there is no method overloading that accept a generic and the two parametersReincarnate
arrg, you saved my a lot of time, thank you!Lawrence
@MartinBrandl Maybe I am on a different version, but it seems that it does accept but hardcode limited to 'json' only.Cerebral
A
30

if you have options

return this.http.post(`${this.endpoint}/account/login`,payload, { ...options, responseType: 'text' })
Anibalanica answered 2/2, 2018 at 10:12 Comment(2)
An explanation would be helpful. http.post allows up to three arguments - what if I need to add a header as well?Hosmer
@Hosmer The header is one of the options: {...options, responseType: 'text', header: yourHeader }Helminthic
A
8

Even adding responseType, I dealt with it for days with no success. Finally I got it. Make sure that in your backend script you don't define header as -("Content-Type: application/json);

Becuase if you turn it to text but backend asks for json, it will return an error...

Archipenko answered 28/3, 2019 at 7:22 Comment(1)
Also you can set as parameters to new object derived from new class. then return this object as response. i.e. you can change your response to JSON formatDeshabille
A
4

I had the same problem and the cause was That at time of returning a string in your backend (spring) you might be returning as return "spring used"; But this isn't parsed right according to spring. Instead use return "\" spring used \""; -Peace out

Abrogate answered 16/11, 2019 at 14:59 Comment(5)
From Review: Hi, this post does not seem to provide a quality answer to the question. Please either edit your answer and improve it, or just post it as a comment.Horst
Alright..SO for eg. in my situation i was using Spring as backend and Angular at frontend. After the correct authentication my spring server has to return me a string "valid" which is processed only if the login info is correct.Abrogate
The problem with my program was similar ie. Http failure during parsing....Then I realised that spring is considering " of my server response as special character.Hence, i had to return a string which backend can also understand... So i returned " \" valid \" " instead of "valid" and \ notation in web is used to specify an " (inverted coma) written inside of the inverted commas of string { " \" \" " instead of " " " " }. And after that error was nowhere to be seen..I hope its more clear now @ sɐunıɔןɐqɐpAbrogate
Thank you for the answer. This worked fine for me too.Simplehearted
thank you , I fix the same angular error, the backend is keyword , I looked through the response from the backend and found that I returned OK("string") , But I should return Ok(new { message = "string" })Yandell
A
3

In my case the problem was a missing "/" in the url call, just after the resource. It was then trying to fetch the angular component (html) instead of the JSON resource. I hope this helps since I did not found the answer to my question in this thread.

Alli answered 31/3, 2021 at 12:11 Comment(1)
this answer gave me a hint to my problem, thanks here is the link to my answer: https://mcmap.net/q/126300/-angular-httpclient-quot-http-failure-during-parsing-quotStarryeyed
L
1

You should also check you JSON (not in DevTools, but on a backend). Angular HttpClient having a hard time parsing JSON with \0 characters and DevTools will ignore then, so it's quite hard to spot in Chrome.

Based on this article

Lavonia answered 6/8, 2019 at 16:36 Comment(0)
S
1

I had the same problem, but in my case I forgot to add the proxy url to the api.

readonly apiUrl = this.appConfigService.appConfig.apiUrl + 'EndPointUrl';

This answer helped me figure it out: https://mcmap.net/q/126300/-angular-httpclient-quot-http-failure-during-parsing-quot

Starryeyed answered 28/10, 2021 at 9:15 Comment(0)
A
1

For my case, I had a line break from PHP results.

E.g.,

echo json_encode($row)."\<br/>";

I removed the <br/> and all was well.

Amon answered 19/4, 2022 at 8:30 Comment(0)
P
1

In my situation I had copied code from the documentation that used an "echo" in my API after querying another API, and the echoed text was aggregated onto the response causing invalid JSON.

Paraesthesia answered 27/10, 2023 at 19:29 Comment(0)
D
0

I was facing the same issue in my Angular application. I was using RocketChat REST API in my application and I was trying to use the rooms.createDiscussion, but as an error as below.

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":"

I have tried couple of things like changing the responseType: 'text' but none of them worked. At the end I was able to find the issue was with my RocketChat installation. As mentioned in the RocketChat change log the API rooms.createDiscussion is been introduced in the version 1.0.0 unfortunately I was using a lower version.

My suggestion is to check the REST API is working fine or not before you spend time to fix the error in your Angular code. I used curl command to check that.

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

There as well I was getting an invalid HTML as a response.

<!DOCTYPE html>
<html>
<head>
<meta name="referrer" content="origin-when-crossorigin">
<script>/* eslint-disable */

'use strict';
(function() {
        var debounce = function debounce(func, wait, immediate) {

Instead of a valid JSON response as follows.

{
    "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
}

So after updating to the latest RocketChat I was able to use the mentioned REST API.

Drone answered 13/5, 2019 at 6:5 Comment(0)
C
0

I use .NetCore for my back-end tasks,I was able to resolve this issue by using the Newtonsoft.Json library package to return a JSON string from my controller.

Apparently, not all JSON Serializers are built to the right specifications..NET 5's "return Ok("");" was definitely not sufficient.

Crosier answered 29/12, 2020 at 6:28 Comment(0)
M
0

Check is your JSON is valid JSON. I experience the exact same issue and I found that I had one extra comma "," in my json. If the JSON is "hardcoded" in the js file, extra comma is not a problem, but if it's served from a server, it's a problem.

Moly answered 20/3, 2023 at 19:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.