nuxt中利用js-cookie保存token,这样token能在headers中获取,并用于vuex,将token存于store中。
1. utils文件下创建auth.js, 封装js-cookie方法
const Cookies = process.client ? require('js-cookie') : undefined
export function getToken (TokenKey) {
return Cookies ? Cookies.get(TokenKey) : ''
}
export function setToken (TokenKey, token) {
return Cookies && Cookies.set(TokenKey, token)
}
export function removeToken (TokenKey) {
return Cookies && Cookies.remove(TokenKey)
}
// 解析cookie中的参数
export function cookieParse (cookie) {
if (!cookie) { return {} }
const cookies = {}
cookie.split(';').forEach(item => {
const parts = item.split('=')
cookies[parts[0].trim()] = parts[1].trim()
})
return cookies
}
2.登录, stroe,actions文件下添加登录和退出登录方法。
import { setToken, removeToken } from '~/utils/auth'
login ({ commit }, params) {
return new Promise((resolve, reject) => {
this.$axios.post(url, params).then(res => {
const token = res.data
setToken('Token', token)
commit('SET_TOKEN', token)
resolve(res)
}).catch(err => {
reject(err)
})
})
}
loginOut ({ commit }) {
return new Promise((resolve) => {
commit('INIT')
removeToken('Token')
resolve()
})
}
3.中间件authenticated。
由于页面刷新后store中的数据会被清空,authenticated从headers中去获取token存于store中。
import { cookieParse } from '~/utils/auth'
export default function ({store, req}) {
if (req && req.headers && req.headers.cookie) {
const parsed = cookieParse(req.headers.cookie)
const token = parsed.Token
if (token) {
store.commit('SET_TOKEN', token)
return token
}
}
}
nuxt.config.js文件中配置authenticated
router: {
middleware: ['authenticated']
}
4.store中添加nuxtServerInit
import { cookieParse } from '~/utils/auth'
nuxtServerInit ({commit, state}, {req}) {
let token = null
if (req && req.headers && req.headers.cookie) {
const parsed = cookieParse(req.headers.cookie)
try {
token = parsed.Token
} catch (err) {
// No valid cookie found
}
commit('SET_TOKEN', token)
}
}
5.axios中配置token
import { getToken } from '~/utils/auth'
config.headers = {
Authorization: getToken('Token')
}