问题发现场景
前端在向后端发送 GET 请求,会多个 OPTIONS 请求,由于 OPTIONS 的时间和 GET 的时间接近,所以想优化它,让它只做一次 GET 请求。

问题分析、优化
- 在各种 google 之后,得知由于前端添加了头部 token 和 source 自定义字段,导致 GET 请求变为非简单请求,所以会在正式通信之前,添加一次 HTTP 预检请求,也就是 OPTIONS 请求。
- 我尝试过不传 header 头时,确实只有一次 GET 请求,但由于业务需要,source 为必传字段,不然没法跟踪请求来源,当有 token 时,也必须要传
- 试着把后端的 Access-Control-Max-Age 设置为 30 天,那样子虽然可以减少 OPTIONS 的请求,但只能减少非第一次请求的,在第一次请求依然会有
想请教下各位大神有木有更好的解决方案?
前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue-Test</title>
<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
</head>
<body>
<div id="app">
{{ info }}
</div>
<script type = "text/javascript">
axios.defaults.headers.common['source'] = 'test';
var url = "https://api.rvhqs.com/v1/home_search_rv_detail/?vehicle_id=661&pickup_branch_id=387&start_date=2019-12-29&end_date=2020-01-01&return_branch_id=387&start_time=10:00&end_time=10:00"
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.get(url)
.then(response => (this.info = response))
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
})
</script>
</body>
</html>
Django 后端 CORS 配置
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_PREFLIGHT_MAX_AGE = 2592000
CORS_ALLOW_HEADERS = default_headers + (
'source',
)