I have 2 NodeJS express services both running in http://localhost:3000. When I run my angular APP(localhost:4200), first service runs fine and load data however the second service from child component issue CORS Error. Could you suggest why?
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.
I don't have CORS-related headers/changes in any of the service. Wondering why the first service works and other service does NOT. The only notable difference is I am calling the first service from ngOnInit and other from 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;
});
}
}
Second service call:
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));
}
}
Looks like the service that caused CORS issue was missing "access-control-allow-origin" header in the original response. So Intercepted and added this header.
router.get('/*', function (req,res, next) {
res.header('access-control-allow-origin','*')
next();
});