请注意,我使用的是 Laravel 框架。另请注意,SO上有类似的问题,我已经检查过了,但无法根据这些解决方案解决我的问题......
即使我根据我的知识设置了我的 CSRF 令牌,但我不确定它为什么不起作用。
检查控制台时,我似乎有 3 个 cookie:两个 Request cookie,其中一个被调用XSRF-TOKEN
,一个被调用laravel_session
。和一个响应laravel_session
饼干。都有不同的价值!!!
我的 Vue:
new Vue({
el:'body',
http: {
root: '/root',
headers: {
'X-CSRF-Token': $('meta[name=_token]').attr('content')
}
},
});
我的头:
<meta name="_token" content="{!! csrf_token() !!}"/>
我的 Vue 组件 addNew 方法:
Vue.component('things',{
template:'#things-panel-template',
data(){
return {
list: [],
newThing: {
body: '',
// _token: $('meta[name=_token]').attr('content'),
// tried removing token from head meta and adding up here.
},
}
},
methods:{
addNew(){
var thing = this.newThing; // get input
this.newThing = {body:''}; // clear input
this.$http.post('/api/things/add',thing) // send
},
},
});
我的路线:
Route::post('/api/things/add',function(){
return App\Thing::create(Request::get());
});
最后,我的 Vue 模板中的表单:
<form action="/things/add"
method="POST"
@submit.prevent="addNew"
>
<div class="form-group">
{{ csrf_field() }}
<label for="">Add</label>
<input type="text"
name="body"
id="task-body"
class="form-control"
v-model="newThing.body"
>
<button :disabled="!isValid"
class="btn btn-primary"
type="submit"
>Add</button>
</div>
</form>