vue.js 本地存储中的Nuxt 3身份验证令牌

dl5txlt9  于 2022-12-19  发布在  Vue.js
关注(0)|答案(1)|浏览(573)

我尝试在我的应用程序中创建登录。我有登录响应,返回access_token并将其添加到localStorage中。我在pinia中的代码

import { defineStore } from 'pinia'
import { axiosInstance } from '@/axios.config'

export const useAuth = defineStore('auth',{
    state: ()=>({
        user:[],
        access_token:[],
    }),

    actions:{
        async loginUser(email:string, password:string){
            try{
                const res = await axiosInstance.post('/login',{email, password,  withCredentials: true,})
                this.user = await res.data.user
                this.access_token = await res.data.access_token
                localStorage.setItem("access_token", res.data.access_token)
               await useRouter().push('/')
              
             }catch(e){
            console.log(e.response.data)
        }
    },

和axios配置:

import axios from 'axios'

const API_URL = 'https://quiz.bojarm.pl/api';

export const axiosInstance = axios.create({
    baseURL: API_URL,
    headers: {
        "Content-Type": "application/json",
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers':  'Content-Type, X-Auth-Token, Authorization, Origin',
        Accept: "application/json",
        Authorization: `Bearer ${localStorage.getItem('access_token')}`,
    },
})

当我尝试登录令牌工作良好,但当我重新加载页面的access_token不工作,注销用户

ulydmbyx

ulydmbyx1#

Axios和**@nuxtjs/axios**不建议与Nuxt 3一起使用

使用useFetch()-它应该可以解决您的问题。
请点击此处了解详情:https://nuxt.com/docs/getting-started/data-fetching/#usefetch

相关问题