设置请求头跨域问题

在后端已经设置了 CORS 的 Access-Control-Allow-Origin 请求头后,如果 AJAX 请求时设置了自定义请求头,依然会报跨域的问题。报错的信息大概是 Access to XMLHttpRequest at 'http://xuanshang.test/login/dev' from origin 'http://practice.test' has been blocked by CORS policy: Request header field dev-token is not allowed by Access-Control-Allow-Headers in preflight response 。这是因为如果要设置自定义请求头,后端还需要根据是否是 OPTIONS 请求方法,设置允许的请求头。这个 OPTIONS 请求称为 预检请求 ,是浏览器在必要的时候,自动发出的。以获取被允许的请求头、请求方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header('Access-Control-Allow-Origin: ' . $allowOrigin);
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Credentials: true');
// 返回允许设置的请求头
header('Access-Control-Allow-Headers: DEV-TOKEN');
header('Access-Control-Max-Age: 86400');
header('Content-Type: text/plain charset=UTF-8');
header('Content-Length: 0');
header('status: 204');
header('HTTP/1.0 204 No Content');
exit;
} else {
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Origin: ' . $allowOrigin);
}