【问题标题】:Angular Response error : SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse角度响应错误:SyntaxError: Unexpected token < in JSON at JSON.parse 的位置 0
【发布时间】:2021-10-19 03:04:26
【问题描述】:

我想从 API 获取我的数据。 API 本身在 postmap 中运行良好,如下所示:

{
    "status": "Success",
    "data": [
        {
            "title": "asus g551 vw",
            "price": 500,
            "image": "https://localhost:44345/images/products/origin/img1.jpg",
            "count": 2
        },
        {
            "title": "asus vivobook",
            "price": 1200,
            "image": "https://localhost:44345/images/products/origin/img1.jpg",
            "count": 2
        },
        {
            "title": "acer predator",
            "price": 200,
            "image": "https://localhost:44345/images/products/origin/img1.jpg",
            "count": 1
        }
    ]
}

但是在 Angular 中,当我调用我的 get 函数时,我从这个 Angular 代码中得到一个错误:

myservice method 'GetUserBasketDetails()' : 

    @Injectable({
      providedIn: 'root'
    })
    export class OrderService {
    
      
      private orderDetails : BehaviorSubject<OrderBasketDto[]> = new BehaviorSubject<OrderBasketDto[]>(null);
    
      constructor(private _http : HttpClient) { }
    
      _SetOrderDetails(details : OrderBasketDto[]){
        this.orderDetails.next(details);
        console.log(this.orderDetails)
      }
    
      _GetOrderDetails() : Observable<OrderBasketDto[]>{
        return this.orderDetails;
      }
    
    
      GetUserBasketDetails():Observable<IResponseResult<OrderBasketDto[]>>{
        return this._http.get<IResponseResult<OrderBasketDto[]>>('/basket-details');
      }
    }

当我在组件中调用它时:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'Front-Project';

  constructor(private _accountService : AccountService,
              private _orderService : OrderService) {
  }

  ngOnInit():void {
    

    this._orderService.GetUserBasketDetails().subscribe(res=>{
      console.log(res)
      
    })

  }
}

这是我得到的错误:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "https://localhost:44345/basket-details", ok: false, ...}

错误:SyntaxError: Unexpected token

console error image

我该如何解决这个问题?

【问题讨论】:

  • 您没有从服务器得到正确的响应。复制 URL 后尝试 curl 请求。
  • 即使状态码是 200 OK,响应似乎包含错误,Unexpected token &lt; in JSON 暗示响应实际上是 HTML 字符串而不是 JSON。
  • 您对映射 IResponseResult 感到满意吗?您是否尝试不映射?如果你有回应?

标签: json angular api syntax-error asp.net-core-webapi


【解决方案1】:

我发现问题是我的 url 错误我忘记在 get 方法中添加 api 控制器名称 像这样'/order/basket-details'

【讨论】:

    猜你喜欢
    • 2021-09-30
    • 2021-07-20
    • 2022-01-04
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2019-05-23
    相关资源
    最近更新 更多