ionic 2 REST API:无法加载网址

时间:2017-09-18 14:53:40

标签: angular ionic-framework ionic2 cordova-2.0.0

运行命令ionic serve时出错。我试图用post方法调用api。

我收到了错误:

  

无法加载http://abc.localhost/api/auth/login:对预检请求的响应未通过访问控制检查:否' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' http://localhost:8101'因此不允许访问。

我怎么能克服这个?

我已经在api模块的YII2框架中编写了api,其行为如下:

 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; }

我的ionic2 cordova api调用脚本是:

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();
  });

即便如此,我也无法在chrome检查中看到帖子参数和身份验证。 提前谢谢!

2 个答案:

答案 0 :(得分:2)

我很想知道这个问题,但我找到了一个简单的解决方案here

我将下面的代码添加到ionic.confog.json

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

现在我使用POST方法从动作http://abc.localhost/api/auth/login调用其余的api。

以前我在尝试使用:

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();
  });

但是我需要像这样打电话给api:

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();
  });

看到差异是调用rest api URL,因为代理路径已在配置文件中设置。 这对我有用。

答案 1 :(得分:1)

在开发过程中,您可以使用CORS plugin for Google Chrome

  

当我们运行或测试我们的应用时,CORS只是一个问题   正在运行ionic serveionic run -l

     

有两种方法可以解决问题:第一种也是更简单的解决方案   只是允许API端点的所有来源。但是,我们做不到   始终控制我们正在访问的端点。那么,我们需要的是一个   请求未指定origin。 - Handling CORS issues in Ionic