【发布时间】:2017-02-17 16:40:56
【问题描述】:
我有这个表单,用户只能在文本区域内输入文本:
<form action="#" v-on:submit="postStatus">{{-- Name of the method in Vue.js --}}
<div class="form-group">
<textarea class="form-control" rows="5" maxlength="140" autofocus placeholder="What are you upto?" required v-model="post"></textarea>
</div>
<input type="submit" value="Post" class="form-control btn btn-info">
{{ csrf_field() }}
</form>
然后,我有这个脚本代码,我在其中使用 vue.js 和 ajax,以便将该文本传递到控制器并最终将其保存到数据库中:
//when we actually submit the form, we want to catch the action
new Vue({
el : '#timeline',
data : {
post : '',
},
http : {
headers: {
'X-CSRF-Token': $('meta[name=_token]').attr('content')
}
},
methods : {
postStatus : function (e) {
e.preventDefault();
console.log('Posted: '+this.post+ '. Token: '+this.token);
$.ajax({
url : '/posts',
type : 'post',
dataType : 'json',
data : {
'body' : this.post,
}
});
}
},
});
但是,到目前为止,这不起作用,因为存在此令牌不匹配异常。我不知道如何使它工作。如何将此令牌值传递给控制器。我尝试了以下方法:
1)在表单里面,我给token添加了一个vue名字:
<input type="hidden" name="_token" value="YzXAnwBñC7qPK9kg7MGGIUzznEOCi2dTnG9h9çpB" v-model="token">
2) 我已经尝试将这个令牌值传递到 vue 中:
//when we actually submit the form, we want to catch the action
new Vue({
el : '#timeline',
data : {
post : '',
token : '',
},
methods : {
postStatus : function (e) {
e.preventDefault();
console.log('Posted: '+this.post+ '. Token: '+this.token);
$.ajax({
url : '/posts',
type : 'post',
dataType : 'json',
data : {
'body' : this.post,
'_token': this.token,
}
});
}
},
});
...但是在控制台中,vue 甚至没有捕捉到它:(
这导致我出现以下错误:
VerifyCsrfToken.php 第 68 行中的 TokenMismatchException:
我该如何解决?有什么想法吗?
【问题讨论】:
-
放一个@符号.... @{{ csrf_field() }}
-
@tam 它使事情变得奇怪。例如,如果我将
@ -
没有@,当你检查 DOM 时,你会看到 csrf 字段吗?
-
@tam 是的,我确实看到了
<input type="hidden" name="_token" value="0NjpnvRbsYPNL3V8gwY40P2HMQMMoqG1noH9eqQ6">,这是{{ csrf_field() }}的输出
标签: laravel vue.js laravel-5.3