gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:25:03 33 4
gpt4 key购买 nike

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

平台:Ionic 4 Angular 7

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

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

当我禁用 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 后问题开始。

header('Status: 400', TRUE, 400); header('Status: 404', TRUE, 404);

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

当我在 service.php 中设置 header 时

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');

include('config.ini.php');

我收到以下错误。

Access to XMLHttpRequest at 'https://mersinders.com/api/service.php?run=giris' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

当我在 .htaccess 中设置 header 时

Header always set Access-Control-Allow-Origin "*" Header always set Access-Control-Allow-Methods "POST, GET,HEAD" Header always set Access-Control-Max-Age "1000"

我收到以下错误。

Access to XMLHttpRequest at 'https://mersinders.com/api/service.php?run=giris' 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.

但是在禁用安全功能的 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策略错误。以及为什么我的 header 仅在 .htaccess 中有效。

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

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

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

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

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

最佳答案

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

在我面临的这段时间。

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

Access to XMLHttpRequest at 'https://mersinders.com/api/service.php?run=giris' from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

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

Access to XMLHttpRequest at 'https://mersinders.com/api/service.php?run=giris' 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.

最后我有以下 service.php header

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 中什么也没有。

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

关于php - 在 ionic 4 上使用 Angular 7 后出现 Cors 策略错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57544527/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com