laravel 5 vue.js csrf 令牌

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44988755/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:16:37  来源:igfitidea点击:

laravel 5 vue.js csrf token

laravelnpmvue.js

提问by Florian

I've been at it for a while to get this csrf token to work with the vue.js example.

为了让这个 csrf 令牌与 vue.js 示例一起工作,我已经研究了一段时间。

but it keeps saying i don't have a token. I've tried all kinds of variations.

但它一直说我没有令牌。我尝试了各种变体。

bottom (not head, before end of body)

底部(不是头部,在身体末端之前)

    <script>
    window.myToken =  <?php echo json_encode([
        '_token' => csrf_token(),
    ]); ?>
    </script>

    <script src="/js/manifest.js"></script>
    <script src="/js/vendor.js"></script>
    <script src="/js/app.js"></script>

html

html

<div id="app">
@section('content')
<example></example>
@endsection
</div>

console output

控制台输出

CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token

vendor.js:7635 You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html

Example doesn't seem to do much either, but I guess i need the token.

示例似乎也没什么用,但我想我需要令牌。

回答by Adnan Mumtaz

if you look into

如果你调查

/resources/assets/js/bootstrap.js

/resources/assets/js/bootstrap.js

You will find

你会找到

let token = document.head.querySelector('meta[name="csrf-token"]');

You should add in your <head>tag this:

你应该在你的<head>标签中添加:

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

This error will not be shown anymore.

将不再显示此错误。

I hope this helps

我希望这有帮助

回答by Minar Mnr

Insert this script into your page headtag.

将此脚本插入到您的页面head标记中。

<script>
   window.Laravel = {
      'csrfToken' => '{{csrf_token()}}',
   };
</script>

In your bootstrap.js:

在您的bootstrap.js

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest'
}