我尝试在我的应用程序中创建登录。我有登录响应,它返回 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 不起作用并注销用户
Axios 和 @nuxtjs/axios 不推荐与 Nuxt 3 一起使用
使用 useFetch() - 它应该可以解决您的问题。
在这里阅读: https://nuxt.com/docs/getting-started/data-fetching/#usefetch
Pinia 存储不持久化。使用本地存储来存储您需要保留的数据。