How to add token when using axios to send an ajax

2019-09-04 17:40发布

问题:

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