问题描述
禁止访问 (403)
CSRF验证失败. 请求被中断.
Reason given for failure:
CSRF token missing or incorrect.
先看所使用的组件
- 在本次遇到的问题中,主要使用了 el-input 和 el-select两种组件
- 先看源代码
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<!-- -->
<link href="{% static 'css/element/index.css' %}" rel="stylesheet">
<script src="{% static 'js/vue/vue_dev.js' %}"></script>
<script src="{% static 'js/element/index.js' %}"></script>
<script src="{% static 'js/axios/axios.min.js' %}"></script>
{# <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">#}
</head>
<body>
<div id="app" style="width: 300px">
<template>
{% csrf_token %}
<el-select v-model="value" placeholder="请选择" style="width: 300px">
<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
</el-option>
</el-select>
</template>
<el-input placeholder="请输入Ip" v-model="device.ip" clearable></el-input>
<el-input placeholder="请输入username" v-model="device.username" clearable></el-input>
<el-input placeholder="请输入password" v-model="device.password" clearable></el-input>
<el-button type="primary" @click="onSubmit">立即创建</el-button>
</div>
</body>
<script>
new Vue({
el: '#app',
data() {
return {
device: {
ip: '',
username: '',
password: '',
},
options: [{
value: '1',
label: 'Windows'
}, {
value: '2',
label: 'Linux'
}],
value: ''
}
},
methods: {
getCookie(name) {
var value = '; ' + document.cookie;
var parts = value.split('; ' + name + '=');
if (parts.length === 2) return parts.pop().split(';').shift()
},
onSubmit() {
var that = this;
that.device['monitortype'] = that.value;
//添加headers 用于解决CSRF Failed: CSRF token missing or incorrect问题
axios.post('/monitor/AddDevice/', that.device, {headers: {'X-CSRFToken': this.getCookie('csrftoken')}})
.then(function (response) {
alert(JSON.stringify(response.data))
})
.catch(function (error) {
console.log(error)
})
}
}
})
</script>
</html>
- 在这个文件中使用了根据不同的组件类型,使用了两种不同的方式进行CSRF的验证
问题解决
- 针对el-select这种组标签,采用了 {% csrf_token %}的 方式
- 对于el-input 这种单标签,采用了getCookie的方式
getCookie(name) {
var value = '; ' + document.cookie;
var parts = value.split('; ' + name + '=');
if (parts.length === 2) return parts.pop().split(';').shift()
},
//添加headers 用于解决CSRF Failed: CSRF token missing or incorrect问题
axios.post('/monitor/AddDevice/', that.device, {headers: {'X-CSRFToken': this.getCookie('csrftoken')}})
验证
-
请求可以正常发送,服务端正常响应
image.png