gpt4 book ai didi

laravel - 如何将 laravel CSRF token 值传递给 vue

转载 作者:搜寻专家 更新时间:2023-10-30 22:07:52 26 4
gpt4 key购买 nike

我有这种形式,用户应该只在文本区域内键入文本:

            <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,以便将该文本传递到 Controller 并最终将其保存到数据库中:

//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,
}
});
}
},
});

但是,到目前为止这还行不通,因为存在 token 不匹配异常。我不知道如何让它工作。如何将此 token 值传递给 Controller ​​。我尝试了以下方法:

1) 在表单内,我为 token 添加了一个 vue 名称:

<input type="hidden" name="_token" value="YzXAnwBñC7qPK9kg7MGGIUzznEOCi2dTnG9h9çpB" v-model="token">

2) 我试图将此 token 值传递到 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 甚至没有捕捉到它:(

这导致我出现以下错误:

TokenMismatchException in VerifyCsrfToken.php line 68:

我该如何解决?有什么想法吗?

最佳答案

非常简单的解决方案只需在表单中添加一个隐藏字段。一个例子

<form id="logout-form" action="/logout" method="POST" style="display: none;">
<input type="hidden" name="_token" :value="csrf">
</form>

现在在 vue 文件的 script 中添加 csrf 变量,就像这样。 (记住,它必须在 data 中)。

<script>
export default {
data: () => ({
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
}),
}
</script>

N.B. 您将在 blade.php 文件中看到这样的元标记。

<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">

如果没有这样的东西,你需要把它放在那里。

关于laravel - 如何将 laravel CSRF token 值传递给 vue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39938284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com