原本的接口写法
router.get('/getSuppList', async (req, res, next) => {
// 获取token
const tk = String(req.headers.authorization || '').split(' ').pop();
if (await token.checkToken(tk) === false) {
res.send({
code: 400,
msg: 'token校验失败'
})
} else {
next()
}
}, async (req, res) => {
const data = await conn.exec('SELECT * FROM Supplier');
if (data.length > 0) {
res.send({
code: 200,
msg: '获取供应商数据成功',
SuppList: data
})
} else {
res.send({
code: 400,
msg: '获取供应商数据失败'
})
}
})
改进后的写法 在接口入口文件处新增中间件 将接口放到token校验中间件下面
app.use(async (req, res, next) => {
// 获取token
const ytoken = String(req.headers.authorization || '').split(' ').pop();
// 校验token是否过期
if (await token.checkToken(ytoken) === false) {
res.send({
code: 400,
msg: 'token过期',
message: '请求被拦截',
Result: false
})
return
} else {
console.log('token校验通过,已被放行');
next()
}
})
最终接口写法变成
router.get('/getSuppList', async (req, res) => {
const data = await conn.exec('SELECT * FROM Supplier');
if (data.length > 0) {
res.send({
code: 200,
msg: '获取供应商数据成功',
SuppList: data
})
} else {
res.send({
code: 400,
msg: '获取供应商数据失败'
})
}
})