0

I have a Vue.js component...

<template>
    <form method="POST" action="/login">
        <button class="btn btn-primary center-block" @click="$emit('buttonClicked')">
            Login
        </button>
    </form>
</template>

<script>
    var axios = require('axios');

    Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');

    export default {
        created: function () {
            axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
        },
        props: ['show'],
        name: "login-component",
        methods: {
            close: function () {
                this.$emit('close');
            },
            buttonClicked: function () {
                axios.post('/login', {data: this.data})
                    .then(function (response) {
                        console.log(response);
                    })
                    .catch(function (error) {
                        console.log(error.message);
                    });
            }
        }
    }
</script>

My csrf exists in meta:

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

But it doesn't pass with the Ajax request instead I get...

419 unknown status and no _token in console->Form Data

What am I doing wrong?

I tried to use...

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
};

But it didn't help.

2
  • If you use require('axios') axios is only available in the same scope, it isn't hoisted to window. Try your latter attempt but without window.. | Also remove the ;, it is invalid syntax (don't forget to check the console please, it have surely shown errors with both issues). Commented Feb 17, 2018 at 11:58
  • Thanks, I tried this axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content'), }; but didn't helped Commented Feb 17, 2018 at 12:26

1 Answer 1

1

I solved by this way:

export default {
        data() {
            return {
                csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            }
        },
...

And inside <form></form>:

<input type="hidden" name="_token" :value="csrf">
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.