【问题标题】:Cors policy error when use Angular 7 post on ionic 4在 ionic 4 上使用 Angular 7 帖子时出现 Cors 策略错误
【发布时间】:2019-12-23 22:51:36
【问题描述】:

我很不高兴发布类似的问题,但花了超过 3 天的时间并无法解决问题。

平台:Ionic 4 Angular 7

当我尝试发布时,我遇到了 cors 政策错误。

从源“http://localhost:8100”访问“https://mersinders.com/api/service.php?run=giris”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。

当我禁用 chrome 安全性时,一切正常。

“C:\Program Files (x86)\Google\Chrome\Application\chrome.exe” --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp

HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request", url: "https://mersinders.com/api/service.php?run=giris", ok: false, ...}

在 Php api 端使用以下标头后开始出现问题。

header('状态:400', TRUE, 400); header('状态:404', TRUE, 404);

我有 config.ini.php,其中包括数据库信息和连接,还有 service.php,其中 switch case "service.php?run=XXXXX" 。

当我在 service.php 中设置标题时

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header('访问控制允许方法:GET、PUT、POST、DELETE、 选项'); header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, 内容处置,内容描述');

include('config.ini.php');

我得到以下错误。

访问 XMLHttpRequest 在 'https://mersinders.com/api/service.php?run=giris' 来自原点 “http://localhost:8100”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:否 'Access-Control-Allow-Origin' 标头出现在请求的 资源。

当我在 .htaccess 中设置标题时

标头始终设置 Access-Control-Allow-Origin "*" 标头始终设置 Access-Control-Allow-Methods "POST, GET, HEAD" 标头始终设置 Access-Control-Max-Age "1000"

我得到以下错误。

访问 XMLHttpRequest 在 'https://mersinders.com/api/service.php?run=giris' 来自原点 'http://localhost:8100' 已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:它没有 HTTP 正常状态。

但在禁用安全功能的 chrome 和 postman 上一切正常。 我也试过了

proxy.config.json

{
    "/api/*": {
        "target": "https://mersinders.com",
        "secure": false,
        "logLevel": "debug"

    }
}

和 ionic.config.json

{
    "name": "mersinders",
    "integrations": {
        "cordova": {}
    },
    "type": "angular",
    "proxies": [{
        "path": "/api/*",
        "proxyUrl": "https://mersinders.com"
    }]
}

和 tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ],
  "proxies": [
    {
      "path": "/api/*",
      "proxyUrl": "https://mersinders.com"
    }
  ]
}

我的帖子功能

 var headers = new HttpHeaders();
    headers.append("Accept", 'application/json');
    headers.append('Content-Type', 'application/json');
    headers.append('Access-Control-Allow-Origin', '*');

    let postData = {
      "username": this.userData.username,
      "password": this.userData.password,
      "clientIp": this.cekIp(),

    }
    console.log(postData);
    this.http.post(environment.SERVER_URL + "service.php?run=giris", postData,{ headers:headers, observe: 'response' })
      .subscribe(response => {
        if (response.status == 200 && response.body[0].ogretmen_token != "") {
          this.isUser.token = response.body[0].ogretmen_token;
          en_isUser.Loggedin = true;
          en_isUser.token = this.isUser.token;
          en_isUser.guid = this.isUser.guid;
          this.status.girisCode = response.status;
          //   this.storage.set('token',this.isUser.token);
          window.localStorage.setItem('token', this.isUser.token);
          this.router.navigate(['/tabs/anasayfa']);
        }
        console.log(this.isUser.token);
      }, error => {
        this.status.girisCode = error.status;
        this.isUpdated = error.error;
        console.log(error);
      });

问题 1) 我们如何解决 cors 策略错误。以及为什么我的标头仅在 .htaccess 中有效。

使用 ionic 4 本机 http 发布工作,但我想使用 Angular 7 Http。感谢您的建议。

编辑:当我检查我看到的服务器日志时; AH01623:客户端方法被服务器配置拒绝:'OPTIONS',

我使用 Postman 检查是否有任何问题。我看到当我从 chrome 发布数据时,邮递员中似乎是“POST”,但在服务器上它是 OPTIONS 并被阻止。

Edit1:经过更多尝试,我看到 https://cors-anywhere.herokuapp.com/ 将 OPTIONS 请求转换为 POST 请求,这就是它在 chrome 上工作的原因。

我尝试通过邮递员发出 OPTIONS 请求,但失败了(405 不允许)。但是来自邮递员的 POST 请求成功。看来后端有问题。有人可以帮助为什么标头在 htaccess 中有效但在 service.php 文件中无效(可能吗?:选项方法可以到达 .htaccess 并在该服务器丢弃该请求之后?)。

【问题讨论】:

    标签: php header cors ionic4 angular-http


    【解决方案1】:

    我花了3天多的时间解决cors问题,终于解决了。问题是 httpd conf 文件中不允许使用 OPTIONS。我按照以下步骤操作。

    在我面临的这段时间里。

    error 1) 这意味着你没有添加 header("Access-Control-Allow-Origin: *");到service.php文件

    访问 XMLHttpRequest 在 'https://mersinders.com/api/service.php?run=giris' 来自原点 'http://localhost:8100' 已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

    错误 2)这意味着“您发布了一些内容,但在发布之前我们要检查安全性,如果服务器没有返回我们状态:200 我们不会发布您的请求”。

    访问 XMLHttpRequest 在 'https://mersinders.com/api/service.php?run=giris' 来自原点 “http://localhost:8100”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:它没有 HTTP 正常状态。

    最后我有下面的 service.php 标题

    if (isset($_SERVER['HTTP_ORIGIN'])) {
    
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
    
    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // may also be using PUT, PATCH, HEAD etc
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
        exit(0);
    }
    

    发布功能

    send(){
     var headers = new HttpHeaders();
        headers.append("Accept", 'application/json');
        headers.append('Content-Type', 'application/json');
        headers.append('Access-Control-Allow-Origin', '*');
    
        let postData = {
          "username": this.userData.username,
          "password": this.userData.password,
          "clientIp": this.cekIp(),
    
        }
        console.log(postData);
        this.http.post(environment.SERVER_URL + "service.php?run=giris", postData,{ headers:headers, observe: 'response' })
          .subscribe(response => {
            console.log(response);
          }, error => {
    
            console.log(error);
          });
    
    }
    

    htaccess 中什么也没有。

    当您尝试解决此问题时,请关注服务器日志。我想为那些不像我花太多时间的人解释它。

    【讨论】:

    • 我试过这个解决方案仍然有问题。我可以在浏览器中成功运行。虽然 ionic cordova 在真实设备中运行 android,但我的 post 请求单独不起作用。来自原点 'localhost' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否 'Access-Control-Allow-Origin ' 请求的资源上存在标头。
    猜你喜欢
    • 2020-11-03
    • 2020-03-12
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 2019-09-08
    • 2020-06-14
    相关资源
    最近更新 更多