【问题标题】:How to Pass CSRF token with AJAX request Laravel + Vue.js如何使用 AJAX 请求 Laravel + Vue.js 传递 CSRF 令牌
【发布时间】:2018-07-28 03:36:04
【问题描述】:

我有一个 Vue.js 组件...

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

我的 csrf 存在于 meta 中:

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

但它没有通过 Ajax 请求,而是我得到...

419 unknown status 并且控制台中没有 _token->Form Data

我做错了什么?

我尝试使用...

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

但这并没有帮助。

【问题讨论】:

  • 如果你使用require('axios') axios 只能在同一个作用域内使用,它不会被提升到window。尝试你的后一种尝试,但没有window.。 |同时删除;,它是无效的语法(请不要忘记检查控制台,这两个问题肯定都显示错误)。
  • 谢谢,我试过 axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content'), }; 但没有帮助

标签: ajax vue.js csrf laravel-5.5


【解决方案1】:

我是这样解决的:

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

&lt;form&gt;&lt;/form&gt;里面:

<input type="hidden" name="_token" :value="csrf">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 2017-12-12
    • 2015-12-20
    • 2014-11-04
    • 2021-08-14
    • 2016-09-19
    • 1970-01-01
    相关资源
    最近更新 更多