当给出上述错误时,尝试从我的angular 8 Web应用程序发出JWT授权的json rest api请求。遵循了所有明智的CORS配置步骤,然后放宽了规则,使其仍然不起作用,我已经向你们寻求帮助。
因此,在CORS配置方面,从我开始的php方面来看:
header("Access-Control-Allow-Origin: http://localhost:4200");
header("Content-Type: application/json;charset=utf-8");
header("Access-Control-Allow-Methods: OPTIONS, GET, PUT, POST, DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
我放松了一点:
header("Access-Control-Allow-Origin: *");
header("Content-Type: *");
header("Access-Control-Allow-Methods: *");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: *");
但是后来我在CORS文档中看到Access-Control-Allow-Headers不允许*,所以我恢复了这一行。
目前我有:
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json, text/plain, */*");
header("Access-Control-Allow-Methods: OPTIONS, GET, PUT, POST, DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, X-Requested-With, Authorization");
我得到的错误是:
在以下位置访问XMLHttpRequest 原产地的“ http://localhost/api/controllers/asset.php/” “ http://localhost:4200”已被CORS政策屏蔽:对 飞行前请求未通过访问控制检查:它没有 HTTP正常状态。
这是调试工具(Chrome)中“网络”标签中请求的标头信息。
显示临时标头接受:application / json,text / plain, / 授权:Beary eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOm51bGwsImF1ZCI6IlRIRV9BVURJRU5DRSIsImlhdCI6MTU2NjYyOTIXNyb ...
这是在php 7.2上的Apache上运行的
我希望新的宽松CORS设置能够正常工作,但仍然会出现此错误。
如何调整CORS设置以满足飞行前的要求?
答案 0 :(得分:0)
我创建了一个名为Willow的框架。这是我使用的code,它超越了CORS的精神错乱。
$requestMethod = $_SERVER['REQUEST_METHOD'];
// Is this a pre-flight request (the request method is OPTIONS)? Then start output buffering.
if ($requestMethod === 'OPTIONS') {
ob_start();
}
// Allow for all origins and credentials. Also allow GET, POST, PATCH, and OPTIONS request verbs
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
header('Access-Control-Allow-Methods: GET, POST, PATCH, OPTIONS, DELETE');
// If this is a pre-flight request (the request method is OPTIONS)? Then flush the output buffer and exit.
if ($requestMethod === 'OPTIONS') {
ob_end_flush();
exit();
}
HTH