Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Unexpected end of JSON input" Angular 5

Tags:

angular

When sending a GET request to API, I'm always getting an error (so the response will fall into the CATCH instead of TRY) even tough status is 200.

Here is the request :

// Check if user exists at blur on email input authentication
checkUserExists( platformId: string, email: string) {
    return this.http.get(checkUserExistsAPI + `/${platformId}/${email}`);
}

As i'm using Angular 5, I took off the .map(res).

And here is the function that uses the request :

// Verify if emails exists
verifyEmail(email) {
    if (email) {
        this.authenticationService.checkUserExists( this.platformId, email )
            .subscribe(
                (data: CheckEmailResponse) => {
                    console.log(data);
                },
                (error: CheckEmailResponse) => {
                    console.log(error);

                }
            );
    }
}

It will never console.log(data) as I'm always getting this error :

error:{
    error: SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at XMLHttpRequest.onLo…, text: ""}
    headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
    message:"Http failure during parsing for http://API.com"
name:"HttpErrorResponse"
ok:false
status:200
statusText:"OK"
like image 996
GreatHawkeye Avatar asked Oct 18 '22 02:10

GreatHawkeye


1 Answers

Ok so I figured it out. The response didn't had any content body and Angular 5 is, by default, expecting a Json formatted content body, therefor it couldn't work. I only needed the status response anyway to know if it was 200 or 404.

I added { responseType: 'text' } to the request as above`:

return this.http.get(checkUserExistsAPI +/${platformId}/${email}, { responseType: 'text' });

So now it managed to go to the TRY of my TRY/CATCH with a data equals to "null". But I don't care about the data as I only care about the status. Anyway, now if the status is 200, it will go into the TRY, if the status is 404, it will go into the CATCH.

like image 72
GreatHawkeye Avatar answered Nov 15 '22 10:11

GreatHawkeye