I have an angular front end website that is trying to hit an endpoint on a webserver. At this point the website is in a proof of concept phase. Here’s the request:
constructor(private http: HttpClient) { }
getData(): Observable<any> {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:4200'
});
return this.http.get(`${this.apiUrl}`, { headers: headers, withCredentials: true}); }
When I directly paste the endpoint URL into the browser I get an XML response with the data. So what is wrong with the request that it is blocked by CORS when running through my webpage but if I paste the URL in the same browser it returns a result?
2
Answers
CORS is only used for Cross-Origin requests, hence the name. When you paste the request to the browser, the request is executed from the same origin and CORS is not involved.
But then called from the Angular app, the origin is different and browser executes CORS protocol.
CORS needs to be configured on the endpoint webserver. The header
'Access-Control-Allow-Origin': 'http://localhost:4200'
,along with other CORS headers should be send from the endpoint webserver in the response, while in your example you send it to the endpoint server instead.You should allow the methods in Cors like this
app.use(cors({
"origin": "*",
methods: [‘GET’,’POST’,’DELETE’,’UPDATE’,’PUT’,’PATCH’]
}));