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

与世无争的帅哥 提交于 2019-12-23 03:33:15

问题


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

<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?


回答1:


have you set AUTH_TOKEN on the window? If not window.AUTH_TOKEN will naturally not be defined.

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

<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

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 vuex for storing it. Doing so will allow you access to it throughout your app, without having to store anything on the window.




回答2:


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



来源:https://stackoverflow.com/questions/40808405/how-to-add-token-when-using-axios-to-send-an-ajax-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!