# 网络请求

WebNuxt的网络请求并未使用Axios,而是使用了Nuxt3推荐的方式 (opens new window),我们对useFetch$fetch进行了封装,使它们具有了有以下特点:

  • 自动携带会员token
  • 自动携带当前语言
  • 可选的 Loading
  • 自动错误/成功提示

# 注意事项

  1. WebNuxt/api目录,存放了系统所有的网络请求函数,我们也建议您将封装的请求函数放置于此目录下。
  2. Http.fetch通常用于获取数据后渲染组件(服务端预渲染获取数据),Http.$fetch则通常用于用户交互后发出请求(组件已经渲染后才会发送的请求,比如用户点击)
  3. 封装的Http.fetchHttp.$fetch无法满足您的使用场景时,当然是可以直接使用useFetch、$fetch的,我们对其封装只是为了方便使用。
  4. Http.fetchHttp.$fetch请求参数几乎一致,只是响应数据结构不一样,分别是res.data.valueres

封装的Http.fetchHttp.$fetch的封装代码位于/utils/request.ts,但通常您参考如下方式创建请求即可:

Http.fetch<DataT = any>(options: FetchOptions<DataT>, config: Partial<FetchConfig> = {}, loading: LoadingOptions = {}): Promise<AsyncData<ApiResponse<DataT>, FetchError | null>>
Http.$fetch<DataT = any>(options: NitroFetchOptions, config: Partial<FetchConfig> = {}, loading: LoadingOptions = {}): Promise<ApiResponse<DataT>>

# Http.fetch使用示例

  • /api/common.ts文件
/**
 * 初始化请求函数
 */
export function initialize() {
    return Http.fetch({
        url: '/api/index/index',
        method: 'get',
    })
}
  • 然后就可以在其他文件内
import { initialize } from '~/api/common'

const { data } = await initialize()
if (data.value?.code == 1) {
    memberCenter.setStatus(data.value.data.openMemberCenter)
    siteConfig.dataFill(data.value.data.site)
}

Http.fetch的返回值与useFetch是一样的,需要注意的是code != 1 仍然会进 then,因为如果抛出异常,将导致服务端渲染时出错;另外有一些其他建议:

  1. 请在请求后判断code == 1才执行成功的逻辑
  2. 请求失败时code != 1,会自动弹出接口返回的错误消息,仍然进then(可关闭弹窗)
  3. 请求出错时,会自动弹出请求错误消息(如404),进catch
  4. 服务端渲染建议使用await的方式发送请求,前台用户点击才发生的请求则随意

# Http.$fetch使用示例

  • 它的参数于以上的Http.fetch几乎一致
  • /api/common.ts文件
/**
 * 请求发送短信函数
 */
export function sendSms(mobile: string) {
    return Http.$fetch(
        {
            url: apiSendSms,
            method: 'POST',
            body: {
                mobile: mobile
            },
        },
        {
            showSuccessMessage: true,
        }
    )
}
  • 然后就可以在其他文件内
import { sendSms } from '~/api/common'

sendSms(18888888888)
.then((res) => {
    if (res.code == 1) {
        console.log('发送成功')
    }
}).finally(() => {
    console.log('请求完成')
})

# 参数解释

# 参数一:options: FetchOptions<DataT>

options参数用于配置useFetch的请求参数,如url、method、query、body、headers等等,详细文档 (opens new window),您也可以直接查看类型定义。

export function initialize() {
    return Http.fetch({
        url: '/api/index/index',
        method: 'get',
        params: {
            params1: 11
        },
        lazy: true,
    })
}

# 参数二:config: Partial<FetchConfig> = {}

config参数可以传递以下可用选项:

选项名 默认值 注释
loading false 是否开启loading层效果
reductDataFormat false 是否开启简洁的数据结构响应(pick = ['data'])
showErrorMessage true 是否开启请求错误信息直接提示,如404
showCodeMessage true 是否开启code!=0时的信息直接提示(比如操作失败直接弹窗提示接口返回的消息,就不需要再写代码弹窗提示了)
showSuccessMessage false 是否开启code=0时的信息直接提示
export function initialize() {
    // 定义了接口响应的 data 类型,此操作是可选的
    return Http.fetch<{user: any}>(
        {
            url: indexUrl,
            method: 'get',
            params: {
                params1: 11,
            },
            lazy: true,
        },
        {
            loading: true,
        }
    )
}

# 参数三:loading: LoadingOptions = {}

我们封装了element plusloading,此参数用于设置loading的配置,所有可用配置项,请参考官方文档 (opens new window)

export function initialize() {
    // 定义了接口响应的 data 类型
    return Http.fetch<{user: any}>(
        {
            url: indexUrl,
            method: 'get',
            params: {
                params1: 11,
            },
            lazy: true,
        },
        {
            loading: true,
        },
        {
            text: '正在全力加载中...'
        }
    )
}