Nuxt3请求封装

325 阅读1分钟

封装(/utils/useHttpFetch.ts)

import {callWithNuxt} from "#app";
// 获取配置的变量


interface myFetchOptions {
    headers?: Record<string, string>, // Record<string, string>表示一个对象,健跟值都是string
    [key: string]: any
}
export const useHttpFetch = (url: string, opt: myFetchOptions = {}) => {
    const runtimeConfig = useRuntimeConfig()
    const token = useCookie('accessToken')
    const headers = {
        ...opt.headers,
        ...(token.value ? {'Authorization': token.value} : {})
    }
    opt.headers = headers

    const nuxtApp = useNuxtApp()
    return useFetch(url, {
        ...opt,
        baseURL: runtimeConfig.public.BASE_URL,
        onRequest({ request, options }) {
            console.log('onRequest')
        },
        onRequestError({ request, options, error }) {
            // Handle the request errors
            console.log('onRequestError')
        },
        onResponse({ request, response, options }) {
            // Process the response data
            console.log('onResponse')
        },
        async onResponseError({ request, response, options }) {
            // Handle the response errors
            console.log('onResponseError')
            if (response.status === 401) {
                alert('401')
                // 跳转回登录页面
                await callWithNuxt(nuxtApp,navigateTo,[
                    "/sign_in",
                    {replace:true,redirectCode:401}
                ])
            } else if (response.status === 500) {
                alert('服务器发生错误')
            }
        }
    })
}

暴露api(/composables/api/***.ts)

import { useHttpFetch } from '@/utils/useHttpFetch'

// 获取标签
export const getmodels = (opt: any) => {
    return useHttpFetch(`/api/getmodels`, opt)
}

使用

const getModels = () => {
   return getmodels({
        query: {
            page: page.value,
            pageSize: 10,
            period: 0,
            sort: 0,
            uid: 'f75b428e0cfdb12fc02e632e98528faf'
        }
   })
}
const { data: listResult } = await getModels()