axios CSRF令牌不匹配Laravel 10和NuxtJS

lokaqttq  于 2023-03-12  发布在  iOS
关注(0)|答案(1)|浏览(169)

我安装的主要问题是我不能用axios发出请求。总是因为CSRF令牌不匹配而得到419,不知道该怎么做,看了google上的每一篇文章,用axios发出请求的例子:

methods: {
    async register() {
        await this.$axios.get('http://localhost:80/sanctum/csrf-cookie');
        await this.$axios.post('http://localhost:80/api/register', {
            name: this.name,
            email: this.email,
            password: this.password,
        });
    }
}

奇怪的是,我可以登录,接收用户和注销刚刚好。像这样:
x一个一个一个一个x一个一个二个x
我确实试过更改域,检查了几次我的设置,一切看起来正常。
我的laravel后端在docker上运行,网址是http://localhost/我的nuxt应用程序在http://localhost:3000/上运行
laravel配置:

SANCTUM_STATEFUL_DOMAINS=localhost:3000
SESSION_DOMAIN=localhost
SESSION_DRIVER=cookie
APP_URL=http://localhost

NuxtJS配置:

export default {
    head: {
        title: 'appname',
        htmlAttrs: {
            lang: 'en'
        },
        meta: [{
                charset: 'utf-8'
            },
            {
                name: 'viewport',
                content: 'width=device-width, initial-scale=1'
            },
            {
                hid: 'description',
                name: 'description',
                content: ''
            },
            {
                name: 'format-detection',
                content: 'telephone=no'
            }
        ],
        link: [{
            rel: 'icon',
            type: 'image/x-icon',
            href: '/favicon.ico'
        }]
    },

    css: [],

    plugins: [],

    components: true,

    buildModules: [
        '@nuxt/typescript-build',
        '@nuxt/postcss8'
    ],

    modules: [
        '@nuxtjs/axios',
        '@nuxtjs/auth-next'
    ],

    axios: {
        credentials: true
    },

    auth: {
        strategies: {
            'laravelSanctum': {
                provider: 'laravel/sanctum',
                url: 'http://localhost',
                endpoints: {
                    login: {
                        url: '/api/login'
                    },
                    logout: {
                        url: '/api/logout'
                    }
                }
            }
        }
    },

    build: {
        transpile: [
            'defu'
        ]
    }
}

我哪里做错了?

ztmd8pv5

ztmd8pv51#

所以当你在sancutum上使用laravel的时候,你需要先获取CSRF令牌,我看到你正在这么做。Axios应该以你的名义附加它,但是你也可能需要设置它。因为你能够登录,然后它失败了,我想知道它是否在请求之间丢失了。你应该检查它是否在随后的请求中。
https://laravel.com/docs/10.x/sanctum#csrf-protection

相关问题