Access to XMLHttpRequest at 'https://authapistaging2.mymonow.com/api/auth/token/create' from origin 'http://localhost:8101' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

authservice.ts

import { Injectable } from ‘@angular/core’;
import {HttpClient, HttpHeaders} from ‘@angular/common/http’;
const apiUrl = ‘https://authapistaging2.mymonow.com/api/auth/token/create’;
@Injectable({
providedIn: ‘root’
})
export class AuthService {

constructor(public http: HttpClient) { }
con(data: any) {
// tslint:disable-next-line: no-shadowed-variable
const headers = new HttpHeaders();
headers.set(‘Access-Control-Allow-Origin’, ‘*’);
headers.set(‘Access-Control-Allow-Methods’, ‘GET,HEAD,PUT,PATCH,POST,DELETE’);
// tslint:disable-next-line:no-debugger
debugger;
return new Promise((resolve, reject) => {
// tslint:disable-next-line: whitespace
this.http.post(apiUrl, JSON.stringify(data)).
subscribe(res => {
// tslint:disable-next-line: whitespace
resolve(JSON.stringify(res));
}, (err) => {
reject(err);
});
});
}
getdata(type: any) {
// tslint:disable-next-line: no-shadowed-variable
return new Promise((resolve, reject) => {
// tslint:disable-next-line: whitespace
this.http.get(apiUrl+type).
subscribe(res => {
resolve(JSON.stringify(res));
}, (err) => {
reject(err);
});
});
}
}

login.page.ts

import { Component, OnInit } from ‘@angular/core’;
import {AuthService} from ‘…/provider/auth.service’;

@Component({
selector: ‘app-logup’,
templateUrl: ‘./logup.page.html’,
styleUrls: [’./logup.page.scss’],
})
export class LogupPage implements OnInit {

constructor(private auth: AuthService) { }
data = { login: ‘’, DialingCode: ‘’, MobileNumber: ‘’, Password: ‘’ };
ngOnInit() {
}
login() {
this.auth.con(this.data).then((res) => {
console.log(res);
}
);
}
}

Don’t:

  • needlessly construct Promises
  • do anything with custom HttpHeaders here
  • abuse any out of laziness
  • manually unmarshal and marshal JSON when dealing with HttpClient
  • use providedIn: 'root'

Do:

  • deal with CORS issues on the server side
  • use codefences when posting
  • give methods descriptive names (as opposed to con)
  • give proper types to all function parameters and return values
  • follow coding conventions when it comes to capitalization: DialingCode is a class, not an object member name

i solve that issue using advanceHTTP plugin Provided by ionic