Vue 2 Laravel 5.3 POST 方法提交令牌不匹配
Vue 2 Laravel 5.3 POST method submit with token mismatch
不确定如何正确设置 csrf_token
。这是我的相关代码
项目-card.vue
<template>
.....
.....
<input v-if="selected == 'name' + product.id" v-model="name" type="text" class="form-control" aria-describedby="basic-addon1" @blur.prevent="updateName">
<form id="update-product-name" :action="'http://localhost:8000/updateProductName/'+product.id" method="POST" style="display: none;">
.....
.....
</template>
<script>
.....
.....
methods:{
updateName(){
document.getElementById('update-product-name').submit();
}
}
.....
.....
</script>
app.blade.php
<head>
.....
<!-- CSRF Token -->
<meta id="token" name="csrf-token" content="{{ csrf_token() }}">
.....
</head>
app.js
Vue.http.headers.common['X-CSRF-TOKEN'] = $("#token").attr("value");
重新加载页面并显示:
TokenMismatchException in VerifyCsrfToken.php line 68:
我做了一些研究,发现我不必在提交的每个表单中都添加 csrf_token
,只需将其放在 head 元标记中即可。但是它似乎不起作用。应该怎么设置?
编辑#1
我做了一些研究,并将 attr("value")
更改为 attr("content")
,但同样的问题也发生在我身上。
正如我在评论中提到的,您收到 TokenMismatchException
的原因是因为未发送 csrf header。
Vue.http.headers.common['X-CSRF-TOKEN'] = $("#token").attr("content");
以上将允许您在使用 Vue-Resource 时包含 csrf header。
您将需要更改表单的行为,以便使用 vue/vue-resource 而不是默认的浏览器提交来提交它。
一种方法是:
updateName() {
let data = {
//Add the data you want to be sent in the request here e.g.
//name: this.name
}
this.$http.post('/updateProductName/' + this.product.id, data)
.then(r => {
//Do something on success
})
.catch(r => console.log(r))
}
希望对您有所帮助!
不确定如何正确设置 csrf_token
。这是我的相关代码
项目-card.vue
<template>
.....
.....
<input v-if="selected == 'name' + product.id" v-model="name" type="text" class="form-control" aria-describedby="basic-addon1" @blur.prevent="updateName">
<form id="update-product-name" :action="'http://localhost:8000/updateProductName/'+product.id" method="POST" style="display: none;">
.....
.....
</template>
<script>
.....
.....
methods:{
updateName(){
document.getElementById('update-product-name').submit();
}
}
.....
.....
</script>
app.blade.php
<head>
.....
<!-- CSRF Token -->
<meta id="token" name="csrf-token" content="{{ csrf_token() }}">
.....
</head>
app.js
Vue.http.headers.common['X-CSRF-TOKEN'] = $("#token").attr("value");
重新加载页面并显示:
TokenMismatchException in VerifyCsrfToken.php line 68:
我做了一些研究,发现我不必在提交的每个表单中都添加 csrf_token
,只需将其放在 head 元标记中即可。但是它似乎不起作用。应该怎么设置?
编辑#1
我做了一些研究,并将 attr("value")
更改为 attr("content")
,但同样的问题也发生在我身上。
正如我在评论中提到的,您收到 TokenMismatchException
的原因是因为未发送 csrf header。
Vue.http.headers.common['X-CSRF-TOKEN'] = $("#token").attr("content");
以上将允许您在使用 Vue-Resource 时包含 csrf header。
您将需要更改表单的行为,以便使用 vue/vue-resource 而不是默认的浏览器提交来提交它。
一种方法是:
updateName() {
let data = {
//Add the data you want to be sent in the request here e.g.
//name: this.name
}
this.$http.post('/updateProductName/' + this.product.id, data)
.then(r => {
//Do something on success
})
.catch(r => console.log(r))
}
希望对您有所帮助!