Koa

安装 koa-jwtjsonwebtoken

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const jwt = require('koa-jwt')

app.use((ctx, next) => {
return next().catch(err => {
if (err.status === 401) {
ctx.body = fail(err.originalError ? err.originalError.message : err.message, 401)
} else {
throw err
}
})
})
app.use(jwt({ secret: 'secret' }).unless({
path: [/^\/api\/user\/login/]
}))

router/users.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const router = require('koa-router')()
const User = require('../models/User.js')
const jwt = require('jsonwebtoken')
const { success, fail } = require('../utils/index.js')

router.prefix('/user')

router.post('/login', async ctx => {
const user = await User.findOne({ where: ctx.request.body, raw: true })
if (!user) {
ctx.body = fail('用户名或密码错误')
} else {
const token = jwt.sign(user, 'secret', { expiresIn: '7d' })
ctx.body = success({ token }, '登陆成功')
}
})

router.get('/profile', async ctx => {
// const token = ctx.request.headers.authorization.split(' ').pop()
const token = ctx.get('Authorization').split(' ').pop()
jwt.verify(token, 'secret', (err, decode) => {
if (err) {
ctx.body = fail(err.message, 401)
} else {
ctx.body = success({ userInfo: decode }, '获取成功')
}
})
})

module.exports = router

Vue

安装 axios

src/utils/request.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store/index.js'
import router from '@/router/index.js'

const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 5000
}, error => {
return Promise.reject(error)
})

service.interceptors.request.use(config => {
if (store.getters.token) {
config.headers.Authorization = `Bearer ${store.getters.token}`
}
return config
})

service.interceptors.response.use(res => {
const {
code,
data,
message
} = res.data
if (code === 200) {
return data
} else if (code === 401) {
ElMessage.error(message)
store.dispatch('user/logout')
router.push('/login')
return Promise.reject(new Error(message))
} else {
ElMessage.error(message)
return Promise.reject(new Error(message))
}
}, error => {
console.log(error.message)
ElMessage.error(error.message)
return Promise.reject(error)
})

export default service

src/permisssion.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import router from '@/router/index.js'
import store from '@/store/index.js'

const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
if (store.getters.token) {
if (to.path === '/login') {
next({ path: '/' })
} else {
if (!store.getters.hasUserInfo) {
await store.dispatch('user/getUserInfo')
}
next()
}
} else {
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
next(`/login?redirect=${to.path}`)
}
}
})