后端配置如下
在settings文件中先注册corsheaders 然后注册中间件corsheaders.middleware.CorsMiddleware
然后在settings文件中配置相关的跨域信息
#允许跨域的源
CORS_ORIGIN_WHITELIST = ("http://localhost:8080",)
#允许带着cookie访问
CORS_ALLOW_CREDENTIALS = True
#允许请求的方法
CORS_ALLOW_WETHODS = (
"GET",
"POST",
"PUT",
"DELETE",
'OPTION'
)
#允许访问的请求头
CORS_ALLOW_HEADERS = (
"XMLHttpRequest",
'token',
'x-requested-with',
'content-type'
)
前端配置如下
// 配置django服务器地址
axios.defaults.baseURL = 'http://127.0.0.1:8000'
// 配置请求携带Cookie
axios.defaults.withCredentials = true
// 配置异步请求
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
// 配置请求头里的token
axios.defaults.headers['token'] = localStorage.getItem("token") || ""
// 配置post请求头
axios.defaults.headers.post['Content-Type'] = 'application/json'