我们可以利用中间件来实现API的权限控制。
创建中间件:server/middleware/auth.ts
,内容如下:
const whiteList = [
'/api/login'
]
export default defineEventHandler((event) => {
if (event.path.startsWith('/api')) {
if (!whiteList.includes(event.path)) {
event.context.auth = { user: 123 }
const token = getHeader(event, 'Authorization')
console.log('token1', token)
console.log('New request: ' + event.path)
if (!token) {
// return createError({
// statusCode: 401,
// message: '1'
// })
setResponseStatus(event, 401)
return {
message: 'x'
}
}
}
}
})
正文完