php-在Slim框架上进行CORS期间的预检授权标头
作者:互联网
现在,我遇到了CORS(跨域资源共享)问题,尤其是在尝试向瘦API发送授权时.我试图删除jquery上的授权标头,它的工作原理就像一个魅力!但是我需要通过api密钥的授权,我不知道如何绕过预检模式(OPTIONS).这是JavaScript代码.
$.ajax({
type:'GET',
url:baseApi+'/code/account',
crossDomain:true,
xhrFields:{
withCredentials:true
},
beforeSend:function(xhr){
$overlay.css('display','block');
xhr.setRequestHeader("Authorization",boot._header);
},
complete:function(xhr){
// complete scope
}
});
在苗条的框架上,我将白名单来源域(www.example.com)设置为Access-Control-Allow-Origin.这是完整的配置
if (isset($_SERVER['HTTP_ORIGIN'])) {
if($_SERVER['HTTP_ORIGIN'] == "http://www.example.com"){
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
}
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: Authorization, authorization, Content-Type");
}
这是完整的请求和响应头
响应标题
HTTP/1.1 404 Not Found
Date: Tue, 14 Feb 2017 14:44:34 GMT
Server: Apache/2.4.23 (Unix) OpenSSL/1.0.2h PHP/5.6.24 mod_perl/2.0.8-dev Perl/v5.16.3
X-Powered-By: PHP/5.6.24
Access-Control-Allow-Origin: http://www.example.com
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Authorization, authorization
Content-Length: 514
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html;charset=UTF-8
请求标题
OPTIONS /code/account HTTP/1.1
Host: api.example.com
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://www.example.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Access-Control-Request-Headers: authorization
Referer: http://www.example.com/account/payout
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,id;q=0.6,ms;q=0.4
Accept: */*
我尝试了其他人的可能解决方案,但没有机会解决此问题.始终显示404,其中包含调用的OPTIONS方法,而不是应有的GET方法.
解决方法:
经过研究和调查,我最终按照@Mika Tuupola的建议,将CORS中间件用于Slim.但是由于我使用的是Slim v2,因此此回购https://github.com/palanik/CorsSlim适合我.如果您使用的是Slim v3,请使用由我们的救助者创建的此回购https://github.com/tuupola/cors-middleware.希望能帮助到你!
标签:slim,php,jquery,cors,authorization 来源: https://codeday.me/bug/20191011/1893967.html