我正在尝试基于 REST 的跨域请求。 两个域将托管在同一台服务器上。
domain1:http://testdata.local - 用于将在域 2 上请求 REST API 的应用程序。
domain2:http://api.testdata.local - 用于处理来自域 1 的 REST API 调用
每个 REST API 调用都有一些域 2 所需的自定义标头。
现在,当我通过 ajax 向域 2 调用 REST API 请求时,我收到 CORS 阻止错误。
以下是我正在尝试的代码:
域 2 上示例 API 请求的 PHP 代码:
class mytest{
public function setOriginPolicy() {
if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] == 'http://testdata.local') {
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'])) {
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
}
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
exit(0);
}
}
public function testrequest(){
$this->setOriginPolicy
$result['config_status'] = 1;
$result['config_msg'] = "request ok";
echo json_encode($result);
}
}
来自域 1 的 AJAX 调用:
var url = "http://api.testdata.local/mytest/testrequest";
$.ajax({
type: 'GET',
url: url,
async: true,
crossDomain:true,
//jsonpCallback: 'jsonCallback',
contentType: "application/x-www-form-urlencoded",
headers:{"API_KEY":"andapikey","APP_VERSION":"1.0","CONFIG_VERSION":"1.0","AUTH_TOKEN": "4a6b1e610e81fa19c76a557049e9fa19"
},
/*beforeSend: function( xhr ) {
xhr.setRequestHeader("API_KEY", "andapikey");
xhr.setRequestHeader("APP_VERSION", "1.0");
xhr.setRequestHeader("CONFIG_VERSION", "1.0");
xhr.setRequestHeader("AUTH_TOKEN", "4a6b1e610e81fa19c76a557049e9fa19");
},*/
success: function(json) {
console.log(json);
},
error: function(e) {
console.log(e.message);
}
});
如果我禁用标头,我会得到响应。
请建议
解决方案:
在 .htaccess 中的允许源标头中添加了自定义标头。
http://benjaminhorn.io/code/setting-cors-cross-origin-resource-sharing-on-apache-with-correct-response-headers-allowing-everything-through/
链接特别感谢本杰明。
下面是我的.htaccess。
Header always set Access-Control-Allow-Origin "http://testdata.local"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin,API_KEY,APP_VERSION,CONFIG_VERSION,AUTH_TOKEN"
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
# Redirect Trailing Slashes...
RewriteCond %{REQUEST_METHOD} !OPTIONS
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_METHOD} !OPTIONS
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>