请求与数据
# 请求与数据
# 配置接口地址
在config文件夹中配置全局的接口地址,包括开发环境接口和正式环境接口
export default {
isRequestProxy: true,
development: {
// 开发环境接口请求
host: 'https://mock.boxuegu.com/mock/3547',
// 开发环境 cdn 路径
cdn: ''
},
test: {
// 测试环境接口地址
host: '/',
// 测试环境 cdn 路径
cdn: ''
},
release: {
// 正式环境接口地址
host: 'https://czri-admin.itheima.net',
// 正式环境 cdn 路径
cdn: ''
}
}
# 封装请求
当前请求已经封装完成,如需修改添加功能等,需要在utils文件夹中的request文件夹进行修改
# 封装api
在项目中为了便于多个页面接口的管理,对于不同的api,采取封装的形式,便于使用和复用
import { request } from '@/utils/request' // 引入封装好的axios请求
import type {
CardListResult,
ListResult,
addListParams,
deleteListParams,
ListCollapseResult,
ListTransferModel,
ListCardsortResult
} from '@/api/model/listModel' // 引入相应的类型
export function getList(params) {
return request.get<ListResult>({
url: '/get-list', //接口地址
params //传递数据
})
}
# 调用接口,获取数据
在页面中直接引用接口,并在对应的页面使用该接口调用,获取数据
import { getList } from '@/api/list' //引用接口
// 获取列表数据
const fetchData = async (val) => {
try {
const res: any = await getList(val) // 调用接口获取数据
} finally {
}
}
# Mock 数据
如果需要进行数据 Mock,在 vite.config.js 中,将 viteMockServe 中配置 localEnabled 为 true ,即可开启 mock server 的拦截。
viteMockServe({
mockPath: 'mock',
localEnabled: true,
}),
# 请求代理
在vite.config.js中进行代理设置,使用Vite的http-proxy。
示例:
export default defineConfig({
server: {
proxy: {
// 字符串简写写法
"/foo": "http://localhost:4567/foo",
// 选项写法
"/api": {
target: "http://jsonplaceholder.typicode.com",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ""),
},
// 正则表达式写法
"^/fallback/.*": {
target: "http://jsonplaceholder.typicode.com",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/fallback/, ""),
},
// 使用 proxy 实例
"/api": {
target: "http://jsonplaceholder.typicode.com",
changeOrigin: true,
configure: (proxy, options) => {
// proxy 是 'http-proxy' 的实例
},
},
},
},
});
完整选项配置详见 此处 (opens new window)