• 当前标签:请求头

程序开发 Nuxt.js客户端、服务端设置请求头

依赖: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 的

2019-07-26 11:00:43 115 0 0
阅读详情
  • 1
前往