【问题标题】:Angular4 app with PHP Api CORS request issue带有 PHP Api CORS 请求问题的 Angular4 应用程序
【发布时间】:2020-01-10 00:05:12
【问题描述】:

我正在尝试在 Angular4 Ionic 应用程序中发布,我已阅读所有堆栈溢出帖子并按照他们所说的做了。在我的 PHP 中,我添加了

header ("Access-Control-Allow-Origin: *");
header ("Access-Control-Expose-Headers: Content-Length, X-JSON");
header ("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header ("Access-Control-Allow-Headers: *");

我能够成功地从 POSTMAN 发布帖子,但通过在 android 中调试应用程序我得到 ...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.

我只是在 angular4 ionic 应用中尝试一个简单的帖子..

getImages() {
       this.http.post(url, {
      title: 'foo',
      body: 'bar',
      userId: 1
    })
      .subscribe(
        res => {
          console.log(res);
        },
        err => {
          console.log("Error occured");
        }
      );
    }

【问题讨论】:

    标签: php angular cors


    【解决方案1】:

    我使用下面的 php 代码解决了这个问题,专门允许来自我的本地主机,当我上线时我将删除它。

    $http_origin = $_SERVER['HTTP_ORIGIN'];

    $allowed_domains = array(
        'http://localhost:8100',
        'localhost',
        '*',
        'localhost:8100',
        'http://www.detdev.co.uk',
        'detdev.co.uk'
    );
    
    if (in_array(strtolower($http_origin), $allowed_domains))
    {  
        // header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Origin: $http_origin");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');
    }
    
    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
            header("Access-Control-Allow-Headers: Authorization, Content-Type,Accept, Origin");
        exit(0);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 2018-01-30
      • 2018-12-08
      • 2019-10-03
      • 2020-01-24
      • 1970-01-01
      • 2017-07-21
      相关资源
      最近更新 更多