This question already has answers here:
Closed last year.
I am new in Angular 5, and I want to send http request but it return CORS error in inspect element.
Error
XMLHttpRequest cannot load http://example.com/account/create. 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. The response had HTTP status code 403.
Below is my code:
postFormData(apiUrl: string, value: Object): Observable<any> {
const body = value;
const headers = new Headers();
const utcOffset = -(new Date().getTimezoneOffset());
headers.append('Content-Type', 'application/json');
headers.append('utc-offset', utcOffset.toString());
headers.append('platform', 'WEB');
headers.append('app-version', '1.00');
headers.append('version', '1.0');
headers.append('accept', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
headers.append('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
if (localStorage.getItem('user')) {
const user = JSON.parse(localStorage.getItem('user'));
headers.append('token', user.token);
headers.append('session', user.session);
}
// const options = new RequestOptions({ headers: headers });
return this.http.post(apiUrl, body, { headers: headers })
.map(this.extractData)
.catch(this.handleServerError);
}
CORS is a tool employed by browsers to prevent one origin (localhost in your case) from accessing resources from another (example.com) without the server explicitly saying you can access it via CORS headers like Access-Control-Allow-Origin
and others.
It is the server that needs to provide those headers in order for you to access it's resources.
Mozilla has a good write up on it here.
// Add CORS header.
Example :
const Url = 'http://localhost:3000/';
const headers = new Headers;
const body = JSON.stringify(
{
title: "data"
});
headers.append('Access-Control-Allow-Origin', '*');
this.http.post(Url, body, { headers: headers })
.pipe(map(res => res))
.catch(err => err);
// you can also use HTTP headers
import { HttpHeaders } from '@angular/common/http';
let header = new HttpHeaders();
header.set('Access-Control-Allow-Origin', '*');
Are you sure you have got http:// part in your apiUrl varialble send as an argument of postFormData function. That http:// part looks very essential while using HttpClient functions.
CORS can only be managed server-side using the Access-Control-Allow-Origin
header.
In your case, when serving Angular client side at localhost:4200
, you have 2 options for the value of this header:
- Add
*
-- this will enable all origins (not recommended in
production environment)
- Add
localhost:4200
(including the port!) -- that will explicit grant
only the domain+port to your server