在 ionic 4 上使用 Angular 7 后出现 Cors 策略错误

abd*_*lah 4 php header cors angular-http ionic4

我很沮丧地发布了类似的问题,但花了 3 天多的时间却无法解决问题。

\n\n

平台:Ionic 4 Angular 7

\n\n

当我尝试发布时,出现 cors 政策错误。

\n\n

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

\n\n

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

\n\n
\n

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

\n
\n\n

HttpErrorResponse\xc2\xa0{标头:HttpHeaders,状态:400,statusText:“错误请求”,url:“ https://mersinders.com/api/service.php?run=giris ”,好的:false,\xc2\ xa0\xe2\x80\xa6}

\n\n

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

\n\n
\n

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

\n
\n\n

我有 config.ini.php 其中包括数据库信息和连接,以及 service.php 切换大小写 "service.php?run=XXXXX" 。

\n\n

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

\n\n
\n

header(\'Access-Control-Allow-Origin: *\');
\n header("Access-Control-Allow-Credentials: true");
\n header(\'访问控制允许方法:GET、PUT、POST、DELETE、\n OPTIONS\'); header(\'Access-Control-Max-Age: 1000\');
\n header(\'Access-Control-Allow-Headers: Content-Type, Content-Range,\n Content-Disposition, Content-Description\');

\n\n

包括(\'config.ini.php\');

\n
\n\n

我收到以下错误。

\n\n
\n

从 origin\n \' http://localhost:8100 \'访问 XMLHttpRequest at\n \' https://mersinders.com/api/service.php?run=giris \' 已被 CORS 策略阻止: 响应预检请求未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

\n
\n\n

当我在 .htaccess 中设置标头时

\n\n
\n

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

\n
\n\n

我收到以下错误。

\n\n
\n

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

\n
\n\n

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

\n\n

代理配置.json

\n\n
{\n    "/api/*": {\n        "target": "https://mersinders.com",\n        "secure": false,\n        "logLevel": "debug"\n\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

和 ionic.config.json

\n\n
{\n    "name": "mersinders",\n    "integrations": {\n        "cordova": {}\n    },\n    "type": "angular",\n    "proxies": [{\n        "path": "/api/*",\n        "proxyUrl": "https://mersinders.com"\n    }]\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

和 tsconfig.app.json

\n\n
{\n  "extends": "../tsconfig.json",\n  "compilerOptions": {\n    "outDir": "../out-tsc/app",\n    "types": []\n  },\n  "exclude": [\n    "test.ts",\n    "**/*.spec.ts"\n  ],\n  "proxies": [\n    {\n      "path": "/api/*",\n      "proxyUrl": "https://mersinders.com"\n    }\n  ]\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我的发帖功能

\n\n
 var headers = new HttpHeaders();\n    headers.append("Accept", \'application/json\');\n    headers.append(\'Content-Type\', \'application/json\');\n    headers.append(\'Access-Control-Allow-Origin\', \'*\');\n\n    let postData = {\n      "username": this.userData.username,\n      "password": this.userData.password,\n      "clientIp": this.cekIp(),\n\n    }\n    console.log(postData);\n    this.http.post(environment.SERVER_URL + "service.php?run=giris", postData,{ headers:headers, observe: \'response\' })\n      .subscribe(response => {\n        if (response.status == 200 && response.body[0].ogretmen_token != "") {\n          this.isUser.token = response.body[0].ogretmen_token;\n          en_isUser.Loggedin = true;\n          en_isUser.token = this.isUser.token;\n          en_isUser.guid = this.isUser.guid;\n          this.status.girisCode = response.status;\n          //   this.storage.set(\'token\',this.isUser.token);\n          window.localStorage.setItem(\'token\', this.isUser.token);\n          this.router.navigate([\'/tabs/anasayfa\']);\n        }\n        console.log(this.isUser.token);\n      }, error => {\n        this.status.girisCode = error.status;\n        this.isUpdated = error.error;\n        console.log(error);\n      });\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

使用 ionic 4 本机 http 进行后期工作,但我想使用 Angular 7 Http。感谢您的建议。

\n\n

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

\n\n

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

\n\n

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

\n\n

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

\n

abd*_*lah 5

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

在我面临的这段时间里。

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

从源“ http://localhost:8100 ”访问“ https://mersinders.com/api/service.php?run=giris ”处的 XMLHttpRequest已被 CORS 策略阻止:无“Access-Control-Allow-Origin” ' 标头存在于所请求的资源上。

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

从源“ http://localhost:8100 ”访问“ https://mersinders.com/api/service.php?run=giris ”处的 XMLHttpRequest已被 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);
}
Run Code Online (Sandbox Code Playgroud)

后期功能

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

}
Run Code Online (Sandbox Code Playgroud)

htaccess 中什么也没有。

当您尝试解决此问题时,请遵循服务器日志。我想向那些不像我那样花太多时间的人解释一下。