Nuxt3封装网络请求

第一步:在 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
      }
    }
  },

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@前端小菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值