NG 服务:一项服务发出 CORS 错误,而其他服务工作正常

NG services: one service issuing CORS error and other service works fine

我 运行 在 http://localhost:3000 中有 2 个 NodeJS Express 服务。当我 运行 我的 angular APP(localhost:4200) 时,第一个服务 运行 可以正常加载数据,但是来自子组件的第二个服务会出现 CORS 错误。你能告诉我为什么吗?

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.

我在任何服务中都没有与 CORS 相关的 headers/changes。想知道为什么第一项服务有效而其他服务无效。唯一显着的区别是我从 ngOnInit 调用第一个服务,从 ngOnChanges 调用其他服务。

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;

    });

  }
}

第二次服务电话:

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;

        });
      }
  }

}

Youtube服务

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

}
}

NowRunningServiceService

@Injectable({
  providedIn: 'root'
})
export class NowRunningServiceService {
pagenum:number=0;
apiUrl ="/now-running/";
  constructor(private http: HttpClient) { }

  getNowRunningMovies() {
    return this.http.get(globals.api_base_href+this.apiUrl+ (++this.pagenum));

  }


}

看起来导致 CORS 问题的服务在原始响应中缺失 "access-control-allow-origin" header。所以拦截并添加了这个 header.

router.get('/*', function (req,res, next) {
  res.header('access-control-allow-origin','*')
  next();
});