第一步:在 composables 文件夹下新增 useHttp.ts 文件
import { message } from 'ant-design-vue';
interface RequestConfig {
baseURL?: string;
headers?: any;
initialCache?: boolean;
lazy?: boolean;
key?: string;
method?: 'GET' | 'POST';
}
export const fetchConfig = {
baseURL: "https://www.baidu.com",
// headers: {
// appid: "bd9d01ecc75dbbaaefce"
// },
}
//请求体封装
function useGetFetchOptions(options: RequestConfig = {}) {
options.baseURL = options.baseURL ?? fetchConfig.baseURL
options.headers = options.headers ?? {}
options.initialCache = options.initialCache ?? false
options.lazy = options.lazy ?? false
// 用户登录,默认传token
// const token = useCookie("token")
// if (token.value) {
// options.headers.token = token.value
// }
return options
}
//http请求封装
export async function useHttp(key: string, url: string, options: RequestConfig = {}) {
options = useGetFetchOptions(options) as RequestConfig
options.key = key
if (options) {
const data = ref(null)
const error = ref(null)
return await $fetch(url, options).then((res: any) => {
data.value = res && JSON.parse(res)
return {
data,
error
}
}).catch(err => {
const msg = err?.data?.data
if (process.client) {
message.error(msg || '服务端错误')
}
error.value = msg
return {
data,
error
}
})
}
let res = await useFetch(url, options)
// 客户端错误处理
if (process.client && res.error.value) {
const msg = res.error.value?.data?.data
message.error(msg || '服务端错误')
}
return res
}
// GET请求
export function useHttpGet(key: string, url: string, options: RequestConfig = {}) {
options.method = "GET"
return useHttp(key, url, options)
}
// POST请求
export function useHttpPost(key: string, url: string, options: RequestConfig = {}) {
options.method = "POST"
return useHttp(key, url, options)
}
第二步:在组件导入使用
import { useHttpGet} from '@/composables/useHttp'
onMounted(() => {
initValue()
})
const resourceList = ref([])
const initValue = async () => {
const res = await useHttpGet('Resources ', '/resources/getPublishedArticle')
}
注意:需要在 nuxt.config.ts 中配置请求代理
nitro: {
devProxy: {
'/api': {
target: 'https://www.liangzhunglobal.com/',
changeOrigin: true,
// pathRewrite: {'^/api': ''},
autoRewrite: true
}
}
},