Monday, 8 May 2017

javascript - How to fix CORS issue http request in Angular 5

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

}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...