Angular:在期望字符串时,JSON.parse遇到位置0处的JSON中未预期的标记c。

4

我不确定在这里做错了什么。

我正在尝试使用此文档中的结帐功能来使用Stripe:https://stripe.com/docs/payments/checkout/accept-a-payment

我已将我的API配置为仅将checkoutid作为字符串返回。 Angular服务只调用控制器。 当我运行代码时,我实际上会得到一个很好的200响应,并且我可以在响应正文中看到checkout id,但Angular会抛出一个错误:

SyntaxError:JSON中未预期的令牌c位于位置0处,JSON.parse()于XMLHttpRequest.onLoad (https://127.0.0.1:4200/vendor.js:18780:51)ZoneDelegate.invokeTask

该服务如下:

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

我正在这样调用它:

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`.
    //   });
  });

如果我查看网络选项卡,可以看到这个:

enter image description here

但是控制台实际上显示的是这个:

enter image description here

有没有人知道为什么?

2个回答

19

可能响应是字符串,而且您没有指定响应类型。 请尝试以下操作

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

默认的响应类型是 json


我是Angular的新手,我做了这个,但它显示了以下错误::error TS2322:类型“'text'”不能分配给类型“'json'”。 - PauAI
脚本是:this.http.get<string>(${url}, {responseType: 'text'}); - PauAI
1
@PauAI:你需要移除泛型转换<string>。应该是this.http.get(\${url}`, {responseType: 'text'});`。更多信息请参见此处:https://dev59.com/UVUL5IYBdhLWcg3wzqyZ - ruth

1
当我的API返回值与Angular中的可反序列化对象不匹配时,我遇到了这个问题。首先,尝试检查您的返回实体。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接