依赖:cookieparser、@nuxtjs/axios
在 plugins/axios.js 中设置请求头:
import { Message } from 'element-ui'
const cookieparser = process.server ? require('cookieparser') : undefined
// eslint-disable-next-line prettier/prettier
export default function (ctx) {
ctx.$axios.onRequest((config) => {
// 客户端设置token
if (process.client) {
if (ctx.store.state.auth) {
config.headers.Authorization = 'bearer ' + ctx.store.state.auth.access_token
config.headers.token = ctx.store.state.auth.access_token
}
}
// 服务端设置token
if (process.server) {
if (ctx.req.headers.cookie) {
const parsed = cookieparser.parse(ctx.req.headers.cookie)
try {
const auth = JSON.parse(parsed.auth)
config.headers.Authorization = 'bearer ' + auth.access_token
config.headers.token = auth.access_token
} catch (err) {
// 找不到有效的Cookie
}
}
}
// 开发模式打印 URL
if (process.env.NODE_ENV !== 'production') {
console.log('Making request to ' + config.url)
// console.log('Making request to ', config)
}
})
ctx.$axios.onResponse((res) => {
// console.log('onResponse ', res)
const code = res.data.code || null
const msg = res.data.msg || ''
if (code) {
if (code !== 0) {
Message.error(msg)
return Promise.reject(msg)
}
}
})
ctx.$axios.onError((error) => {
const code = parseInt(error.response && error.response.status)
if (code === 400) {
ctx.redirect('/400')
}
})
}
然后在 store 的 actions 中的 nuxtServerInit 中通过req的cookie设置store,将token保存在store中
const cookieparser = process.server ? require('cookieparser') : undefined
export const state = () => ({
auth: null
})
export const mutations = {
setAuth(state, auth) {
// console.log(auth)
state.auth = auth
}
}
export const actions = {
nuxtServerInit({ commit }, { req }) {
let auth = null
if (req.headers.cookie) {
const parsed = cookieparser.parse(req.headers.cookie)
try {
auth = JSON.parse(parsed.auth)
} catch (err) {
// 找不到有效的Cookie
}
}
commit('setAuth', auth)
}