我有2个均在http://localhost:3000中运行的NodeJS Express服务。当我运行我的有角度的APP(localhost:4200)时,第一个服务运行正常并加载数据,但是子组件的第二个服务发出CORS错误。你能建议为什么吗?
<T extends any>
我在任何服务中都没有与CORS相关的标题/更改。想知道为什么第一项服务有效而其他服务无效。唯一值得注意的区别是我正在从ngOnInit调用第一个服务,而从ngOnChanges调用其他服务。
Access to XMLHttpRequest at 'http://localhost:3000/yt-vid/Shazam!' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
第二次服务呼叫:
export class NowRunningComponent implements OnInit {
constructor(private nowrunningService: NowRunningServiceService) { }
movies: Array<Movie>=[];
selectedMovie: Movie;
ngOnInit() {
console.log("MOvies length"+ this.movies);
this.nowrunningService.getNowRunningMovies().subscribe((data:any) => {
this.movies= data.results;
});
}
}
YoutubeService
export class MovieDetailComponent implements OnInit,OnChanges {
@Input()
selectedMovie:Movie;
constructor(private ytService: YoutubeService) { }
ngOnInit() {
console.log('movie detail init');
}
videos:Array<any>=[];
ngOnChanges(changes: SimpleChanges) {
console.log('movie changed');
console.log(`Changes: ${JSON.stringify(changes)})`);
if(this.selectedMovie != null && this.selectedMovie.title!= null)
{
this.ytService.getYTvideos(this.selectedMovie.title).subscribe((data:any) => {
this.videos= data.items;
});
}
}
}
NowRunningServiceService
@Injectable({
providedIn: 'root'
})
export class YoutubeService {
search_url:string = "/yt-vid/";
constructor(private http:HttpClient) { }
getYTvideos (title:string) {
console.log("Youtube service called");
return this.http.get(globals.api_base_href+this.search_url+title);
}
}
答案 0 :(得分:0)
看起来导致CORS问题的服务在原始响应中缺少“ access-control-allow-origin”标头。因此拦截并添加了此标头。
router.get('/*', function (req,res, next) {
res.header('access-control-allow-origin','*')
next();
});