nuxt3中使用useFetch请求刷新不返回数据或返回html结构问题解决-完整nuxt3useFetchtch请求封装

  • 前言

如果使用nuxt3写项目,可以查看nuxt3实战:完整的 nuxt3 + vue3 项目创建与useFetch请求封装,此篇内容有详细步骤

但在此篇内容中useFetch请求在页面有多个请求的情况下,或者放在客户端渲染情境下是失败的,所以在此篇更新下useFetch的请求封装方法:

ts 复制代码
/**
 * @description  useFetch
 * */
import type { NitroFetchRequest } from "nitropack";
import type { UseFetchOptions } from "#app";
import type { ResultData } from "~/api/interface";
import { Base64 } from "js-base64";
import { rsaEncrypt } from "~/utils/ras";
import { Encrypt } from "~/utils/aes";
import { md5 } from "js-md5";

const apiRequest = <T>(
  url: NitroFetchRequest,
  reqParams: object = {},
  _object: UseFetchOptions<T>
) => {
  const runtimeConfig = useRuntimeConfig();
  const token = useCookie<string | undefined>("token");

  const defaultOptions: UseFetchOptions<T> = {
    baseURL: runtimeConfig.public.baseAPI,

    onRequest({ options }) {
      let _data: {
        [prop: string]: any;
      } = {
        ...reqParams,
      };

      if (token.value) {
        _data["userUuid"] = token.value;
      }
      // Gets the current timestamp
      const timestamp = new Date().getTime();
      // Generate an AES Key
      const aesKey = Base64.encode("jupai" + timestamp);
      // Service parameter aes encryption
      // console.log(_data, "_data");

      let reqContent = encodeURIComponent(
        Encrypt(JSON.stringify(_data), aesKey)
      );
      // md5 signature
      const md5Sign = md5(reqContent).toUpperCase();
      // UrlDecode Decrypts the public key
      const rsaSign = encodeURIComponent(rsaEncrypt(aesKey));
      const params = {
        version: "1.0.0",
        osType: "1",
        reqContent: reqContent,
        md5Sign: md5Sign,
        rsaSign: rsaSign,
        timeStamp: timestamp,
        gps: "gps",
        _data,
      };

      options.headers = {
        ...(token.value && { "X-Access-Token": token.value }),
        ...(_object.headers || {}),
        ...options.headers,
      } as { [key: string]: string };
      options.body = JSON.stringify(params);
    },

    onResponse({ response }) {
      if (response._data.code !== "200" && response._data.code !== "12010") {
        if (import.meta.client) {
          message.error(response._data.message);
        }
      }
    },

    onResponseError({ response }) {
      if (import.meta.client) {
        message.error(response._data.message);
      }
    },
  };

  return useFetch<ResultData<T>>(url, {
    ...defaultOptions,
    ..._object,
  } as any);
};

export const getApi = async <T>(
  url: NitroFetchRequest,
  reqParams: object = {},
  _object: UseFetchOptions<T> = {}
) => {
  const { data } = await apiRequest<T>(url, reqParams, {
    method: "get",
    ..._object,
  });
  return data;
};

export const postApi = async <T>(
  url: NitroFetchRequest,
  reqParams: object = {},
  _object: UseFetchOptions<T> = {}
) => {
  const { data } = await apiRequest<T>(url, reqParams, {
    method: "POST",
    ..._object,
  });
  return data;
};
  • 使用:
  • /api/modules/index
ts 复制代码
export const getList= (params: ReqLotList) => {
  return postApi<ResLotList[]>("/api/getList", params);
};
  • index.vue
ts 复制代码
const list= await getList({
  pageNum: 1,
  pageSize: 8
});
相关推荐
一斤代码1 小时前
vue3 下载图片(标签内容可转图)
前端·javascript·vue
sunbyte6 小时前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | DoubleVerticalSlider(双垂直滑块)
前端·javascript·css·vue.js·vue
普宁彭于晏9 小时前
Uni-app 生命周期与钩子:程序的“生命”旅程
uni-app·vue
你喜欢喝可乐吗?14 小时前
RuoYi-Cloud 验证码处理流程
java·spring cloud·微服务·vue
魂兮归乡16 小时前
B2、进度汇报(— 25/06/16)
经验分享·spring boot·ai·vue·团队开发·课程设计·web app
灰海17 小时前
封装WebSocket
前端·网络·websocket·网络协议·vue
布兰妮甜1 天前
开发在线商店:基于Vue2+ElementUI的电商平台前端实践
前端·javascript·elementui·vue
大菠萝学姐2 天前
基于Spring Boot和Vue的高校图书馆座位预约系统的设计与实现
java·vue.js·spring boot·后端·python·mysql·vue
黄焖鸡能干四碗2 天前
系统安全设计方案,软件系统安全设计方案
开发语言·数据库·安全·vue·系统安全
知识分享小能手2 天前
Vue3 学习教程,从入门到精通,使用 VSCode 开发 Vue3 的详细指南(3)
前端·javascript·vue.js·学习·前端框架·vue·vue3