我试图在vue组件中使用一个表单。问题是它不接受我的csrf令牌。我尝试以多种方式添加它,使用
{{!! csrf_field()!!}} // the component does not render after this然后我尝试添加xcsrf
blade.php
>meta name="csrf-token" content="{{ csrf_token() }}">然后将其添加到脚本中
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
}); //this gives error token mismatch然后,我尝试将xcsrf添加到挂载函数中,如下所示
mounted() {
this.csrf = window.laravel.csrfToken
} // I get the error csrfToken of undefined这是我的代码app.js
//new vue component
Vue.component('search', require('./components/Searchnames.vue'));component.vue
<template>
<div class="row">
<form class="col-md-12" action='/table' method="POST">
<input type="hidden" name="_token" :value="csrf">
<h1 class="mainheading">
I have found the following names matching your search
</h1>
<br/>
<br/>
<br/>
<div class='names_container' v-for="name in names">
<button class=" btn-default btn-block glow-border names" type='submit' v-on:click="getName">
{{name.label.eng}}
</button>
</div>
</form>
</div>
</template>
<script>
export default {
data: function () {
return {
names: [],
selected: "",
csrf: ""
};
},
methods: {
getData: function () {
let self = this;
self.$http.jsonp(url, {
jsonpCallback: "JSON_CALLBACK"
})
.then(response => {
response.body.map(function (obj) {
if (obj.type == 'org') {
self.names.push(obj)
}
});
console.log(JSON.stringify(this.names))
})
},
getName: function (element) {
this.selected = element.target.innerText
}
},
mounted: function () {
this.csrf = window.laravel.csrfToken ;
this.getData();
}
}
</script>blade.php模板
@section('content')
<div>
<search></search>
</div>
@endsection
<script>
var url = '{{ $url }}'.replace(/&/g, '&');
</script>发布于 2017-06-14 12:53:30
尝尝这个
Vue.http.interceptors.push(function (request, next) {
request.headers['X-CSRF-TOKEN'] = Laravel.csrfToken;
next();
});然后尝试这个,或者将它添加到您的app.blade.php头中:
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>https://stackoverflow.com/questions/44545302
复制相似问题