laravel 使用axios发送ajax请求时如何添加token?

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

How to add token when using axios to send an ajax request?

ajaxlaravelvue.jsaxios

提问by zwl1619

I am using Laravel 5.3and vue.js 2.0
And I use axios (https://github.com/mzabriskie/axios) to send ajax requests,
I follow the docs to set the TOKENlike this:

我使用的是 Laravel5.3和 vue.js 2.0
我使用 axios ( https://github.com/mzabriskie/axios) 发送 ajax 请求,
我按照文档设置TOKEN如下:

<script>

    axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;  //The error is at this line.

    new Vue({
        el: "#app",
        data: function () {
            return {
                items: []
            }
        },
        mounted: function () {
            this.$nextTick(function () {
                axios.get('/articles').then(function (response) {
                    response.data.forEach(function (item) {
                        item.selected = false;
                    });
                    this.items = response.data;
                }).catch(function (error) {

                    console.log(error);
                });
            });
        }
    });
</script>

the error in console is like this:

控制台中的错误是这样的:

Uncaught ReferenceError: AUTH_TOKEN is not defined 

What should I do?

我该怎么办?

回答by GuyC

have you set AUTH_TOKENon the window? If not window.AUTH_TOKENwill naturally not be defined.

AUTH_TOKEN在窗户上设置了吗?如果不是window.AUTH_TOKEN自然不会被定义。

A common set up in the head of a laravel app is:

Laravel 应用程序的头部常见设置是:

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

This would therefore set the csrf token. I wouldn't imagine this is how you'll be setting an Auth token so you'll probably just need to look into why you are calling window.AUTH_TOKEN

因此,这将设置 csrf 令牌。我不会想象这就是您设置 Auth 令牌的方式,因此您可能只需要研究一下为什么要打电话window.AUTH_TOKEN

In terms of how you generate your token that is dependant on what type you require but once you have it you may want to look instead at vuexfor storing it. Doing so will allow you access to it throughout your app, without having to store anything on the window.

就如何生成令牌而言,这取决于您需要什么类型,但是一旦拥有它,您可能想要查看vuex来存储它。这样做将允许您在整个应用程序中访问它,而无需在窗口上存储任何内容。

回答by ctf0

it should be

它应该是

axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content')

and you can remove the

你可以删除

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

part

部分