如何在 vue 模板中引用 laravel csrf 字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45523101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to refer laravel csrf field inside a vue template
提问by Tanmay
I have a vue template that contains a form:
我有一个包含表单的 vue 模板:
<form id="logout-form" :action="href" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
In laravel, forms must have a csrf_field() defined. But within a vue component, the statement {{ csrf_field() }}
means that I have a method named csrf_field
in my vue instance and I am calling it.
在 laravel 中,表单必须定义一个 csrf_field()。但是在 vue 组件中,该语句{{ csrf_field() }}
意味着我csrf_field
在 vue 实例中命名了一个方法,我正在调用它。
How do I add csrf_field under this circumstance?
这种情况下如何添加csrf_field?
回答by linktoahref
If you have the token in the meta tag of your header (view)
如果您在标题的元标记中有令牌(视图)
<meta name="csrf-token" content="{{ csrf_token() }}">
you could access the token using
您可以使用访问令牌
data() {
return {
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content')
}
}
And add a hidden input field within the form and bind the csrf property to the value like this:
并在表单中添加一个隐藏的输入字段并将 csrf 属性绑定到这样的值:
<form id="logout-form" :action="href" method="POST" style="display: none;">
<input type="hidden" name="_token" :value="csrf">
</form>
回答by omarjebari
If you're using axios with Vue2 for your ajax requests you can just add the following (usually in your bootstrap.js file):
如果您将 axios 与 Vue2 一起用于 ajax 请求,您只需添加以下内容(通常在您的 bootstrap.js 文件中):
window.axios.defaults.headers.common = {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'X-Requested-With': 'XMLHttpRequest'
};
回答by Smokegun
This is how i use it:
这是我如何使用它:
{!! csrf_field() !!}
Put that in your form.
把它放在你的表格里。
and in your vue script you can simply
在你的 vue 脚本中,你可以简单地
methods: {
submitForm: function(e) {
var form = e.target || e.srcElement;
var action = form.action;
get the form and his action then the data value will be:
获取表单和他的操作,那么数据值将是:
data: $(form).serialize()
This works perfectly for me and gives no errors at all.
这对我来说非常有效,并且完全没有错误。