对 ... 处的 XMLHttpRequest 的访问已被 CORS 策略阻止:预检响应中的 Access-Control-Allow-Heders 不允许请求标头字段内容类型。
API 正在其他域中工作,但是当我尝试从我的子域调用 API 时,它给出了此错误。 我尝试在代码中使用一些标头,但 API 返回 CORS 错误。
我的 request.php 页面的代码
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
header('Content-type: application/json');
$data = [ 'msisdn' => '1111', 'result' => 'success', 'message' => 'hi' ];
echo $a=json_encode( $data );
我找到了解决办法。
if (isset($_SERVER['HTTP_ORIGIN'])) {
// allow all origins
header("Access-Control-Allow-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']}");
}
}