核心功能: - 项目初始化 (Nuxt 4 + Nuxt UI + Pinia + ofetch) - TypeScript 类型定义 (User, Article, Comment, API 响应) - 认证系统 (登录/登出、Cookie 支持、权限中间件) - 文章列表页 (筛选、分页、响应式布局) - 文章详情页 (Markdown 渲染、评论系统) - 文章编辑器 (左右分栏、实时预览、Markdown 工具栏) 管理后台: - 侧边栏布局、权限检查 - 数据分析 (数据统计卡片、热门文章、评论审核统计) - 文章管理 (表格、筛选、删除) - 评论管理 (审核通过/拒绝、删除) - 用户管理 (角色管理、删除) 全局组件: - 导航栏 (暗色模式切换、移动端菜单) - 页脚 - 403/404 错误页 配置文件: - .env.example 环境变量模板 - nuxt.config.ts 完整配置 - 自定义 CSS 样式
40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
import type { FetchOptions } from 'ofetch'
|
|
|
|
export function useApi() {
|
|
const config = useRuntimeConfig()
|
|
const apiBase = config.public.apiBase as string
|
|
|
|
const fetch = ofetch.create({
|
|
baseURL: apiBase,
|
|
credentials: 'include',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
})
|
|
|
|
const request = async <T>(url: string, options?: FetchOptions): Promise<T> => {
|
|
try {
|
|
return await fetch<T>(url, {
|
|
...options,
|
|
credentials: 'include',
|
|
})
|
|
} catch (error: any) {
|
|
if (error.status === 401) {
|
|
const authStore = useAuthStore()
|
|
authStore.clearUser()
|
|
}
|
|
throw error
|
|
}
|
|
}
|
|
|
|
return {
|
|
get: <T>(url: string, options?: FetchOptions) => request<T>(url, { ...options, method: 'GET' }),
|
|
post: <T>(url: string, body?: any, options?: FetchOptions) =>
|
|
request<T>(url, { ...options, method: 'POST', body }),
|
|
put: <T>(url: string, body?: any, options?: FetchOptions) =>
|
|
request<T>(url, { ...options, method: 'PUT', body }),
|
|
delete: <T>(url: string, options?: FetchOptions) =>
|
|
request<T>(url, { ...options, method: 'DELETE' }),
|
|
}
|
|
}
|