【问题标题】:ionic 2 REST API : Failed to load urlionic 2 REST API:无法加载网址
【发布时间】:2018-02-27 04:07:03
【问题描述】:

运行命令 ionic serve 时出现错误。我正在尝试使用 post 方法调用 api。

我得到了错误:

无法加载http://abc.localhost/api/auth/login:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 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 检查中看不到发布参数和身份验证。 提前致谢!

【问题讨论】:

    标签: angular ionic-framework ionic2 cordova-2.0.0


    【解决方案1】:

    我想知道很多关于这个问题,但我找到了一个简单的解决方案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,因为代理路径已在配置文件中设置。 这对我有用。

    【讨论】:

      【解决方案2】:

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

      CORS 仅在我们运行或测试我们的应用程序时出现问题 运行ionic serveionic run -l

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

      【讨论】:

      • 感谢托米斯拉夫的回答!我尝试运行命令ionic cordova run -l 在设备上运行应用程序。它告诉我无法加载abc.localhost/api/auth/login:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'localhost:8100'。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 2019-04-30
      • 2017-04-30
      • 2017-12-06
      • 2020-06-21
      • 1970-01-01
      相关资源
      最近更新 更多