Reputation: 459
I'm making an angular web app where I'm making HTTP requests to an API hosted on Firebase to fetch data using post request but I'm getting the following error when the page loads
Failed to load https://chat-f0225.firebaseapp.com/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access
Here is my code
user.service.ts
import { Injectable } from '@angular/core';
import { User } from '../model/User';
import { Methods } from '../model/Method';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/Observable/of';
import { HttpClient , HttpHeaders } from '@angular/common/http'
@Injectable()
export class UserService {
tickets:User[];
method:Methods;
postUrl = 'https://chat-f0225.firebaseapp.com'
data:Observable<any>;
httpOptions = {
headers : new HttpHeaders({'Content-Type':'application/json',
'Access-Control-Allow-Origin': '*'})
};
constructor(private http: HttpClient) { }
getTickets(method:Methods):Observable<User[]>
{
return this.http.post<User[]>(this.postUrl,method,this.httpOptions);
}
}
User.component.ts
import { Component , OnInit} from '@angular/core';
import { User} from '../../model/User';
import { UserService } from '../../services/user.service';
import { Methods } from '../../model/Method';
@Component({
selector : 'app-user',
templateUrl : './user.component.html',
styleUrls : ['./user.component.css'],
})
export class UserComponent implements OnInit{
//Properties
tickets : User[];
method:Methods;
constructor(private userService: UserService)
{
}
ngOnInit()
{
this.method={name:"FetchTickets",userId:"dke1kor"};
console.log("here");
this.userService.getTickets(this.method as Methods).subscribe(ticket =>{
console.log(ticket);
})
}
}
How do I access that API?
Upvotes: 0
Views: 54
Reputation: 1523
You run into an issue with CORS. CORS has to be handled properly at server-side. The Server must send an 'Access-Control-Allow-Origin' where the accessing hosts are whitelisted or * for all Hosts.
see https://enable-cors.org/ for further details.
Upvotes: 1