CORS阻止iTunes API进行角度应用

时间:2019-11-16 23:41:19

标签: angular typescript http

我正在尝试从iTunes api获取一些数据。但是我收到以下错误:

Access to XMLHttpRequest at 'https://itunes.apple.com/search?term=drake' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
api.service.ts:39 0
api.service.ts:42 Something is wrong!
zone.js:3243 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://itunes.apple.com/search?term=drake with MIME type text/javascript. See https://www.chromestatus.com/feature/5629709824032768 for more details.

有什么主意吗?我尝试了proxy.conf.json方法,但未成功。

我的service.ts是:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';


@Injectable({
  providedIn: 'root'
})
export class ApiService {

  api: string = 'https://itunes.apple.com/search?term=drake';

  constructor(
    private http: HttpClient,
  ) { }

  public getAll() {
    return this.http.get(this.api)
    .pipe(
      catchError(this.handleError)
    );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.log(error.error.message)

    } else {
      console.log(error.status)
    }
    return throwError(
      console.log('Something is wrong!'));
  };
}

1 个答案:

答案 0 :(得分:0)

api网址必须为:

https://itunes.apple.com/search?term=drake&enitity=album

已解决