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
});
相关推荐
宇珩前端踩坑日记11 小时前
Vite 代理下的 POST 请求跨域问题排查与解决方案
javascript·vue
前端没钱15 小时前
el-table中的某个字段最多显示两行,超出部分显示“...详情”,怎么办
前端·css·vue
zhanggongzichu20 小时前
跨端兼容——请让我的页面展现在电脑、平板、手机上
前端·css·vue·自适应·响应式·跨端兼容
寰宇软件2 天前
PHP商会招商项目系统小程序
小程序·uni-app·vue·php
寰宇软件2 天前
PHP填表统计预约打卡表单系统小程序
小程序·uni-app·vue·php
飞翔的佩奇3 天前
Java项目: 基于SpringBoot+mybatis+maven+mysql实现的健身房管理系统(含源码+数据库+毕业论文)
java·数据库·spring boot·mysql·vue·毕业设计·健身房
tekin4 天前
Vue.js组件开发
前端·javascript·vue.js·vue·vue组件·vue.js组件开发
大模型铲屎官4 天前
前端框架中 HTML 的应用技巧:React、Vue、Angular 深度解析
react.js·前端框架·vue·html·编程·html5·angular
码农研究僧4 天前
Vue 图片引用方式详解:静态资源与动态路径访问
vue·路由·image·public