基于nuxt.js的项目,用户登陆后请求的接口需要加上token,但是客户端存储到本地的token服务端是拿不到的,这时有两种解决方案:一种是判断当为客户端且已登录时主动带上token再请求一次接口(但是这种感觉不太友好,因为多了一次请求);另一种是想办法把token共享给服务端,这个时候session便派上用场了(express-session可能有内存泄漏的风险,因此采用cookie-session)
0、安装依赖
npm i express cookie-session body-parser -S
1、在项目根目录下新建server.js
const { Nuxt, Builder } = require('nuxt') const bodyParser = require('body-parser') const session = require('cookie-session') const app = require('express')() // Body parser,用来封装 req.body app.use(bodyParser.json()) // Sessions 来创建 req.session app.use(session({ secret: 'zxr', resave: false, saveUninitialized: true, cookie: { maxAge: 2*24*60*60*1000 } })) app.post('/shareNuxt/login', function(req, res){ req.session.authUser = req.body res.json({ code: 0 }) }) app.post('/shareNuxt/logout', function(req, res){ delete req.session.authUser res.json({ code: 0 }) }) // const isProd = process.env.NODE_ENV === 'production' let config = require('./nuxt.config.js') config.dev = !isProd const nuxt = new Nuxt(config) // 生产模式不需要 build if(!isProd){ const builder = new Builder(nuxt) builder.build() } app.use(nuxt.render) app.listen(9999, () => { console.log('Server is listening on http://localhost:9999') })
2、修改命令
例如原来是这样:
"devTest": "cross-env MY_API_ENV=test nuxt"
修改后类似这样:
"devTest": "cross-env MY_API_ENV=test node server.js"
3、vuex中类似这样
import axios from 'axios' export const state = ()=>({ authUser: null }) export const actions = { nuxtServerInit(store, { req }){ if(req.session && req.session.authUser){ store.commit('update_authUser', req.session.authUser) }else{ store.commit('update_authUser', null) } }, async shareLogin({ commit }, data){ let res = await axios.post('/shareNuxt/login', data) if(res.data.code === 0){ commit('update_authUser', data) } }, async shareLogout({ commit }){ let res = await axios.post('/shareNuxt/logout', {}) if(res.data.code === 0){ commit('update_authUser', null) } } } export const mutations = { update_authUser(state, info){ state.authUser = info } }
4、调用
登录调用:
// 共享用户信息至session this.$store.dispatch('shareLogin', { token: res.data }).then(() => { // ... })
退出调用:
this.$store.dispatch('shareLogout')
有朋自远方来...评论一下呗O(∩_∩)O