javascript - Vue 无法从 laravel 刀片获取 CSRF 令牌
问题描述
我有一个带有此代码的刀片。
<meta name="csrf-token" content="{{ csrf_token() }}">
<covid-form>
</covid-form>
然后在我的 covid-form 组件中,我得到了这样的表单:
<form @submit.prevent="send">
<input type="hidden" name="_token" :value="csrf">
我的组件脚本。
<script>
export default {
data(){
return{
csrf: document.head.querySelector('meta[name="csrf-token"]').content,
fullname:'',
phone:'',
nationality:'',
have_not_travelled_to_china:false,
have_not_travelled_to_others:false,
have_not_travelled_to_asian:false,
no_issue_to_stay_home:false,
no_symptomps:false,
dont_have_close_contact:false,
signDate:new Date(),
opts:{
format: 'YYYY-MM-DD',
showClear: true,
showClose: true,
useCurrent: false,
},
date: new Date(),
opt:{
format: 'YYYY-MM-DD HH:mm A',
showClear: true,
showClose: true,
useCurrent: false,
}
}
},
created(){
console.log(this.csrf)
},
methods:{
async send(){
let loader = this.$loading.show({
container: this.fullPage ? null : this.$refs.formContainer,
onCancel: this.onCancel,
color: '#c91010',
loader: 'bars',
width: 80,
height: 100,
})
await axios.post('/submitForm',{
agent_name: this.fullname,
phone: this.phone,
nationality: this.nationality,
have_not_travelled_to_china: this.have_not_travelled_to_china,
have_not_travelled_to_others: this.have_not_travelled_to_others,
have_not_travelled_to_asian: this.have_not_travelled_to_asian,
no_issue_to_stay_home: this.no_issue_to_stay_home,
no_symptomps: this.no_symptomps,
dont_have_close_contact: this.dont_have_close_contact,
signDate: this.signDate,
date: this.date
})
.then(()=>{
swal.fire({
title: 'Success!',
icon: 'success',
width: '500px'
});
loader.hide()
})
}
}
}
</script>
更新:我在控制台中没有任何错误。127.0.0.1:8000/submitForm
使用 post 请求在邮递员中尝试过。但每次我提交我都得到了"message": "CSRF token mismatch.",
。我还删除了刀片中的@csrf,因为它已经在标题中
解决方案
您必须_token
像使用其他属性一样将属性添加到 axios 数据中:
await axios.post('/submitForm',{
_token: this.csrf,
agent_name: this.fullname,
// ...
})
这是post
请求所必需的。
并且由于您将数据设置为 axios,因此来自 data 函数
data() {
return{
csrf: document.head.querySelector('meta[name="csrf-token"]').content,
agent_name: this.fullname,
//...
},
},
您可以删除此行
<input type="hidden" name="_token" :value="csrf">
你根本没有使用它。
此外,您还需要将X-Requested-With
标头设置为 axios 请求,但可能您已经有了类似的东西。
包含在
VerifyCsrfToken
中间件组中的web
中间件将自动验证请求输入中的令牌与会话中存储的令牌是否匹配。
您可以在文档中阅读更多信息:
CSRF 保护
推荐阅读
- mysql - 从 3 个相关表中获取数据
- php - 在 Woocommerce 中的自定义支付网关上获取并传递订单 ID
- pandas - 非常慢的简单熊猫应用功能
- scala - 将 Set 转换为cats.data.NonEmptySet?
- javascript - 如何将 MathJax 作为依赖项包含在内
- javascript - 画布透明填充样式没有完全覆盖现有内容
- excel - 通过将链接模板与单元格中的文本连接来创建超链接 - Excel VBA
- c++ - 在 windbg "x /2" 结果中强制执行 vftable 条目,要考虑什么?
- ios - 从 Swift 项目中删除 Obj-C 头文件时 Xcode 给出随机错误
- matlab - 带有显示周末间隙的时间表数据的蜡烛棒图