[Fixed] Angular Unexpected token c in JSON at position 0 at JSON.parse when expecting a string

Issue

I am not sure what I am doing wrong here.

I am trying to use the checkout facility for stripe using this documentation: https://stripe.com/docs/payments/checkout/accept-a-payment

I have configured my API to just return the checkoutid as a string.
The Angular service just calls the controller. When I run my code I actually get a nice 200 response and I can see the checkout id in the response body, but Angular throws an error:

SyntaxError: Unexpected token c in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (https://127.0.0.1:4200/vendor.js:18780:51) at ZoneDelegate.invokeTask

The service looks like this:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

import { environment } from '@environments/environment';

@Injectable({
  providedIn: 'root',
})
export class StripeService {
  private endpoint: string = 'stripe';

  constructor(private http: HttpClient) {}

  checkout(priceId: string) {
    return this.http
      .get<string>(`${environment.apiUrl}/${this.endpoint}/${priceId}`)
      .pipe(
        map((response) => {
          console.log(response);
          return response;
        })
      );
  }
}

and I am invoking it like this:

this.stripeService
  .checkout(this.button.priceId)
  .subscribe((checkoutId: string) => {
    console.log(checkoutId);
    // this.stripe
    //   .redirectToCheckout({
    //     sessionId: checkoutId,
    //   })
    //   .then(function (result) {
    //     // If `redirectToCheckout` fails due to a browser or network
    //     // error, display the localized error message to your customer
    //     // using `result.error.message`.
    //   });
  });

If I look in the network tab I can see this:

enter image description here

But the console actually shows this:

enter image description here

Does anyone have a scooby why?

Solution

Probably the response is a string and you haven’t specified the response type. Try the following

this.http.get<string>(
  `${environment.apiUrl}/${this.endpoint}/${priceId}`, 
  { responseType: 'text' }
)

Default response type is json.

Leave a Reply

(*) Required, Your email will not be published