1.使用vuecli工具引入axios
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'dayjs/locale/zh-cn'
import zhLocale from 'element-plus/lib/locale/lang/zh-cn'
import 'element-plus/lib/theme-chalk/index.css'
import axios from 'axios'
import vueaxios from 'vue-axios'
createApp(App).use(store).use(router).use(ElementPlus,{ zhLocale }).use(vueaxios,axios).mount('#app')
2.使用axios拦截器添加请求头带上csrftoken字符串
this.axios.interceptors.request.use((config) => {
config.headers["X-Requested-With"] = "XMLHttpRequest";
let regex = /.*csrftoken=([^;.]*).*$/; // 用于从cookie中匹配 csrftoken值
config.headers["X-CSRFToken"] =
document.cookie.match(regex) === null
? null
: document.cookie.match(regex)[1];
console.log(document.cookie);
return config;
});
3.手动将csrftoken写入cookie的方法
1、手动调用 csrf 中的 get_token(request) 或 rotate_token(request) 方法
from django.middleware.csrf import get_token ,rotate_token
def server(request):
# get_token(request) // 两者选一
# rotate_token(request) // 此方法每次设置新的cookies
return render(request, ‘xxx.html‘)
2、在django的HTML模板中添加 {% csrf_token %}
<form action="/login/" method="post">
{% csrf_token %}
......
</form>
3、在需要设置cookie的视图上加装饰器 ensure_csrf_cookie()
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def server(request):
return render(request,'xxx.html')