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
});
相关推荐
java水泥工12 小时前
酒店客房管理系统|基于SpringBoot和Vue的酒店客房管理系统(源码+数据库+文档)
spring boot·vue·酒店管理系统·酒店客房管理系统
爱看书的小沐2 天前
【小沐学WebGIS】基于Three.JS绘制飞行轨迹Flight Tracker(Three.JS/ vue / react / WebGL)
javascript·vue·webgl·three.js·航班·航迹·飞行轨迹
知识分享小能手3 天前
微信小程序入门学习教程,从入门到精通,WXS语法详解(10)
前端·javascript·学习·微信小程序·小程序·vue·团队开发
知识分享小能手4 天前
微信小程序入门学习教程,从入门到精通,WXSS样式处理语法基础(9)
前端·javascript·vscode·学习·微信小程序·小程序·vue
sniper_fandc4 天前
Vue3双向数据绑定v-model
前端·vue
知识分享小能手4 天前
微信小程序入门学习教程,从入门到精通,WXML(WeiXin Markup Language)语法基础(8)
前端·学习·react.js·微信小程序·小程序·vue·个人开发
叫兽~~5 天前
vite vue 打包后运行,路由首页加载不出来
vue.js·vue
岁岁岁平安6 天前
SpringBoot3+WebSocket+Vue3+TypeScript实现简易在线聊天室(附完整源码参考)
java·spring boot·websocket·网络协议·typescript·vue
硅谷工具人6 天前
vue3边学边做系列(3)-路由缓存接口封装
前端·缓存·前端框架·vue
whltaoin7 天前
Vue 与 React 深度对比:技术差异、选型建议与未来趋势
前端·前端框架·vue·react·技术选型