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

问题描述 投票:0回答:1

我有两个运行在http://localhost:3000的NodeJS快递服务。当我运行我的角度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相关的标头/更改。想知道为什么第一个服务工作和其他服务不。唯一值得注意的区别是我从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;

        });
      }
  }

}

YoutubeService

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

  }


}
angular angular-services
1个回答
0
投票

看起来导致CORS问题的服务在原始响应中缺少“access-control-allow-origin”标头。所以Intercepted并添加了这个标题。

router.get('/*', function (req,res, next) {
  res.header('access-control-allow-origin','*')
  next();
});
© www.soinside.com 2019 - 2024. All rights reserved.