此问题已经在这里有了答案:
我正在使用Angular应用程序,在该应用程序中,我使用Flickr API获得了相册和照片的列表。以下是我创建的用于使用Flickr API的服务]
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { GlobalsService } from './globals.service';
import * as Rx from 'rxjs';
interface Response {
photosets: PhotoSets;
}
interface PhotoSets {
page: number;
pages: number;
photoset: PhotoSet[];
length: number;
}
interface PhotoSet {
id: string;
description: String;
title: String;
}
interface String {
_content: string;
}
interface PhotoSetByIds {
photoset: PhotoSetById;
}
interface PhotoSetById {
id: string;
owner: string;
ownername: string;
page: number;
pages: number;
per_page: number;
perpage: number;
photo: Photo[];
primary: string;
title: string;
total: string;
}
interface Photo {
length: number;
farm: number;
id: string;
isfamily: number;
isfriend: number;
ispramy: string;
ispublic: number;
secret: string;
server: string;
title: string;
}
@Injectable({
providedIn: 'root'
})
export class FlickrServiceService {
constructor(private http: HttpClient, private globals: GlobalsService) {
}
getPhotoSets() {
return this.http.get<Response>(
'https://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=' +
this.globals.apiKey +
'&user_id=' +
this.globals.userId +
'&format=json&nojsoncallback=1'
);
}
getPhotos(photosetId: any) {
return this.http.get<PhotoSetByIds>(
'https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=' +
this.globals.apiKey +
'&photoset_id=' +
photosetId +
'&user_id=' +
this.globals.userId +
'&format=json&nojsoncallback=1'
);
}
}
事实是,当我尝试获得某物时,出现以下CORS错误:
从https://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key= &[user_id =对XMLHttpRequest的访问&format = json&nojsoncallback = 1'已被CORS策略阻止:CORS策略不允许请求标头字段授权-飞行前响应中的Control-Allow-Headers。core.js:4002错误HttpErrorResponse {标题:HttpHeaders,状态:0,statusText:“未知错误”,url:“http://localhost:4200... ser_id = 170538248 @ N08&format = json&nojsoncallback = 1”,好的:否,...}
我仍然不知道如何解决这个问题。有什么帮助吗?谢谢!
在app.module.ts中导入HttpClientModule,HttpClientJsonpModule
https://api.flickr.com/services/rest/?method=flick
在FlickrService中,您应该使用jsoncallback而不是nojsoncallback。
import { HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';
@NgModule({
imports: [HttpClientJsonpModule, HttpClientModule]
})
export class AppModule { }
最后在您的组件中,
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class PhotoService {
imagesUrl = `https://api.flickr.com/services/....../format=json&jsoncallback=JSONP_CALLBACK`;
constructor(private http: HttpClient) { }
getPhotos() {
return this.http.jsonp(this.imagesUrl, 'JSONP_CALLBACK');
}
}
希望这会对您有所帮助。