至于为什么会有options请求看阮一峰的一篇文章跨域资源共享 CORS 详解吧
前两天,小伙伴调用我服务器的api遇到options请求403了,我很纳闷..同一套接口,只有登录接口options请求403,其他接口都是正常的
马上看到Preview的报错是
Header not allowed
,就应该知道是header头中加了跨域设置中不允许加的header头然后我仔细看了两个请求图,在Request Headers中,前者多了一个
content-type
字段
我允许跨域的字段在基础字段上只增加了三个,并不允许
content-type
字段,所以就导致了这次403
'allowedHeaders' => [
'nonce','sign','timestamp'
],
再一次验证了我的猜测
由于我用的是laravel-cors插件,直接定位到 vendor/barryvdh/laravel-cors/src/CorsService.php
// if allowedHeaders has been set to true ('*' allow all flag) just skip this check
if ($this->options['allowedHeaders'] !== true && $request->headers->has('Access-Control-Request-Headers')) {
$allowedHeaders = array_map('strtolower', $this->options['allowedHeaders']);
$headers = strtolower($request->headers->get('Access-Control-Request-Headers'));
$requestHeaders = explode(',', $headers);
//这里我们去打印一下我们传的header头和允许添加的header头
var_dump($requestHeaders,$allowedHeaders);
foreach ($requestHeaders as $header) {
if (!in_array(trim($header), $allowedHeaders)) {
// 就是在这里抛出的403
return $this->createBadRequestResponse(403, 'Header not allowed');
}
}
}
发现请求的header头中多了一个
content-type
然而我们在$allowedHeaders中并未允许,所以就报Header not allowed
array(4) {
[0]=> string(12) "content-type"
[1]=> string(5) "nonce"
[2]=> string(4) "sign"
[3]=> string(9) "timestamp"
}
array(3) {
[0]=> string(5) "nonce"
[1]=> string(4) "sign"
[2]=> string(9) "timestamp"
}
添加config/cors.php配置文件
allowedHeaders
中添加content-type
'allowedHeaders' => [
'nonce','sign','timestamp','content-type'
],