Gokulanathan KN
Gokulanathan KN

Reputation: 61

how to unblocked by CORS policy

i tried apiurl in post method for signup page…

import { Injectable } from '@angular/core';
import { Http, Headers, HttpModule } from '@angular/http';
import 'rxjs/add/operator/map';

  let apiUrl = 'http://aaaaa.in/outfit/index.php/api/v1/';

  @Injectable()
 export class AuthServiceProvider {

   constructor(public http: Http) {
   console.log('Hello AuthServiceProvider Provider');
 }
 public register(data){
  return new Promise((resolve, reject) => {
  let headers = new Headers();
  alert('11');
    headers.append('Content-Type', 'application/json');
    headers.append('Access-Control-Allow-Origin', '*');
     headers.append( 'Access-Control-Allow-Headers', 'Authorization, Content-Type' );

    //headers.append('Access-Control-Allow-Origin', 
 'http://localhost:8100');
 //headers.append('Access-Control-Allow-Credentials', 'true');

    alert(apiUrl);
    this.http.post(apiUrl+'account', JSON.stringify(data), {headers: headers})

      .subscribe(res => {
        resolve(res.json());
       alert(Response);
      }, (err) => {
        reject(err);
      });
});

  }

} 

it shows the error like this…“Access to XMLHttpRequest at ‘http://aaaaa.in/outfit/index.php/api/v1/account’ from origin ‘http://localhost:8100’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.”

Thanks in advance..

Upvotes: 1

Views: 1875

Answers (2)

Oliver Primo
Oliver Primo

Reputation: 327

Are you trying to run the application on chrome? If you are running the application on chrome, it usually happens and I don't even know why but it works fine if you try it on an actual device. I encountered the same problem and I overcome it with the help of a chrome extension which is Allow-Control-Allow-Origin. I don't know if there is a proper way to solve this but this might help you 😊

Upvotes: 1

Jaykant Jha
Jaykant Jha

Reputation: 698

Method 1: Install "Allow-Control-Allow-Origin" extension in chrome to resolve this issue for developing.

Method 2: You need to change some lines in ionic.config.json

{
  "name": "foresight",
  "app_id": "47182aef",
  "type": "angular",
  "integrations": {
    "cordova": {}
  },
  "proxies": [
    {
      "path":"/account",
      "proxyUrl": "https://api-foresight.castingapi.in/account"
    }
  ]
}

you can call your external service using the below code

headers = new Headers({'key': '12345678'});
options = new RequestOptions ({headers: this.headers}); 
return this.http.get('/account/?fields=name', this.options)

Remember to ionic serve or ionic lab after making changes in the ionic.config.js

Upvotes: 0

Related Questions