【问题标题】:ionic app cannot connect to php app due to cors由于cors,离子应用程序无法连接到php应用程序
【发布时间】:2016-12-12 22:45:14
【问题描述】:

以下是我的离子代码。进行 API 调用的 Angular 服务。

 var login = function (user)
    {
      return $q(function(resolve, reject)
      {
        $http.post(API_ENDPOINT.url + '/login',user)
          .then(function (result)
          {
            if(result.data.success)
            {
              resolve(result.data.msg);
            }
            else
            {
              reject(result.data.msg);
            }
          });
      });
    };

下面是php端的代码

$app    =   new \Slim\Slim();
// Get request headers as associative array
$headers                = $app->request->headers;
$http_origin            = $headers['Origin'];
$allowed_http_origins   = array("http://localhost","http://localhost:80",
    "http://localhost:8080","http://localhost:63342","null",
    "http://localhost:8100","http://localhost:8888","http://localhost:8889");

if (in_array($http_origin, $allowed_http_origins)){  
    $app->response->headers->set('Access-Control-Allow-Origin',"$http_origin");
}

$app->response->headers->set('Access-Control-Allow-Methods','GET, PUT, POST, DELETE, OPTIONS');
$app->response->headers->set('Access-Control-Allow-Credentials','true');
$app->response->headers->set('Access-Control-Allow-Headers','*');
$app->response->headers->set('Access-Control-Allow-Origin',"$http_origin");


$app->post('/login/', 'Login' );

该应用的 CORS 存在问题,它给出了 Access-Control-Allow-Origins not present 的错误。

【问题讨论】:

  • 尝试将Access-Control-Allow-Origin 的集合更改为*,如果这样做,则意味着您的$http_origin 不包含正确的值
  • @entre 我已经试过了,但没有用
  • 我发现 Ionic CLI 的代理服务器在这种情况下很有帮助:blog.ionic.io/handling-cors-issues-in-ionic
  • 如果没有看到预检请求和您对它的响应,很难提供帮助。但是我看到的Access-Control-Allow-Headers: * 是无效的。 Access-Control-Allow-Headers 不能包含通配符,而是标题列表。对预检的响应不应包含正文,仅包含 2xx 响应和标头。

标签: php angularjs ionic-framework cors


【解决方案1】:

localhost 测试时会出现问题,而将其构建到设备时不会出现问题。

您可以尝试THIS chrome 插件来解决 CROS。

【讨论】:

    猜你喜欢
    • 2021-05-23
    • 2015-07-19
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 2015-01-13
    相关资源
    最近更新 更多