简体   繁体   中英

ionic 2 REST API : Failed to load url

I have the error while running the command ionic serve. I am trying to call the api using post method.

I got the error:

Failed to load http://abc.localhost/api/auth/login : 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:8101 ' is therefore not allowed access.

How can I overcome on this?

I have written the api's in YII2 framework in api module with below behaviour:

 public function behaviors() {
     $behaviors = parent::behaviors();
     $behaviors['contentNegotiator'] = [
         'class' => 'yii\filters\ContentNegotiator',
         'formats' => [
             'text/html' => Response::FORMAT_JSON,
             'application/json' => Response::FORMAT_JSON,
             'application/xml' => Response::FORMAT_XML,
         ],
     ];
     $behaviors['corsFilter'] = [
         'class' => \yii\filters\Cors::className(),
         'cors' => [
             'Origin' => ['*'],
             'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
             'Access-Control-Request-Headers' => ['*'],
             'Access-Control-Allow-Credentials' => true,
             'Access-Control-Max-Age' => 86400,
             'Access-Control-Allow-Origin' => ['*', 'http://abc.localhost/*', 'http://localhost:8101/*']
         ],
     ];
     return $behaviors; }

And my ionic2 cordova api call script is:

loading.present();
console.log(this.singleton.apiGuestToken);
let headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json');
headers.append('Authorization', this.singleton.apiGuestToken);
headers.append('withCredentials', 'true');
headers.append('Access-Control-Allow-Origin', 'http://abc.localhost');

let options = new RequestOptions({ headers: headers });
console.log(options);
let paramsData = { 'userType': userType, 'email': this.email, 'password': this.password };
console.log(paramsData);
this.http.post('http://abc.localhost/api/auth/login', paramsData, options)
  .map(res => res.json()) //this.singleton.apiUrl +
  .subscribe(data => {
    let resultData = JSON.parse(data['_body']);
    console.log(resultData);
       }, error => {
    console.log(error);// Error getting the data
    loading.dismiss();
  });

Even, I can't see the post parameters and Authentication in the chrome inspect. Thanks in advance!

I wonder lots of for this issue but I found a simple solution here

I added below code into ionic.confog.json

{
  "name": "MyApp",
  "app_id": "",
  "integrations": {
    "cordova": {}
  },
  "proxies": [
    {
      "path": "/api",
      "proxyUrl" : "http://abc.localhost/api/"
    }
  ],
  "type": "ionic-angular"
}

Now I am calling the rest api from the action http://abc.localhost/api/auth/login using POST method.

Previously I was trying using:

this.http.post('http://abc.localhost/api/auth/login', paramsData, options)
.subscribe(data => {
    let resultData = JSON.parse(data['_body']);
    console.log(resultData);
       }, error => {
    console.log(error);// Error getting the data
    loading.dismiss();
  });

But I was needed to call api like this:

this.http.post('api/auth/login', paramsData, options)
.subscribe(data => {
    let resultData = JSON.parse(data['_body']);
    console.log(resultData);
       }, error => {
    console.log(error);// Error getting the data
    loading.dismiss();
  });

See the difference is calling rest api URL as proxies path was already been set in config file. This works for me.

During development you can use CORS plugin for Google Chrome .

CORS is only an issue when we are running or testing our app when running ionic serve or ionic run -l .

There are two ways to solve the issue: The first, and easier, solution is to just allow all origins from your API endpoint. However, we can't always control the endpoint we are accessing. What we need, then, is a request that does not specify an origin . - Handling CORS issues in Ionic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM