React/Vue项目-请求文件封装(Axios,WebSocket)

一、Axios

1、Axios封装(request.js)
javascript 复制代码
import axios from "axios";

// 开发环境配置
const baseURL = "/api";

// 生产环境配置
// const baseURL = 'http://192.168.0.1:9000'

// 创建axios实例
const http = axios.create({
  baseURL: baseURL,
  timeout: 5000, // 超时时间
});

// 设置默认请求数据格式
http.defaults.headers.post["Content-Type"] = "application/json;charset=utf-8";

// 请求拦截
http.interceptors.request.use(
  (request) => {
    return request;
  },
  (error) => {
    return error;
  }
);

// 响应拦截
http.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    return error;
  }
);

export default http;
2、示例(api.js)
javascript 复制代码
import http from './request'

// get请求(params = {})
function getRequest(params) {
  return http.get(`/api?user=${params.user}&passwd=${params.passwd}`)
}

// post请求(params = {})
function postRequest(params) {
  return http.post('/api', params)
}

// put请求(params = {})
function putRequest(params) {
  return http.put('/api', params)
}

// delete请求(params = {})
function deleteRequest(params) {
  return http.delete('/api', {
    data:params
  })
}

export default {
    getRequest,
    postRequest,
    putRequest,
    deleteRequest
}

二、WebSocket

1、Ws封装(WebSocket.js)
javascript 复制代码
let ws = null;
let _data = null;
let _url = null;
let _callback = null;
let hearBeatTimer = null;
let reconnectTimer = null;
let reconnectNum = 0; // 重连次数
const time = 3000; // 心跳间隔
const reconnectTime = 5000; // 重连超时

// 初始化
export function webSocket(url = "", data = "", callback = () => { }) {
  _url = url; // 地址
  _data = data; // 发送消息
  _callback = callback; // 回调函数,利用闭包
  createWebSocket(); // 创建 webSocket
}

// 获取连接
export function getWebSocket() {
  return ws;
}

// 创建连接
function createWebSocket() {
  if (!_url) return;
  if (ws) {
    ws.close();
    ws = null;
  }
  ws = new WebSocket(_url);
  ws.onopen = function () {
    sendMessage();
    heartBeat();
  };
  ws.onmessage = function (e) {
    if (typeof _callback === "function") {
      _callback(e);
    }
    reconnectNum = 0;
    heartBeat();
  };
  ws.onerror = function () {
    // console.log('链接失败,正在重连');
    reconnect();
  };
  ws.onclose = function () {
    reconnect();
  };
}

// 关闭连接
export function closeWebSocket() {
  if (ws) {
    ws.onerror = () => { };
    ws.onclose = () => { };
    ws.close();
  }
  ws = null;
  _data = null;
  _url = null;
  _callback = () => { };
  hearBeatTimer = null;
  reconnectTimer = null;
}

// 心跳检测
function heartBeat() {
  if (hearBeatTimer) {
    clearTimeout(hearBeatTimer);
  }
  hearBeatTimer = setTimeout(() => {
    // console.log("ws连接状态:", ws.readyState);
    if (ws && ws.readyState < 2) {
      // 如果连接正常
      sendMessage();
    } else {
      reconnect();
    }
  }, time);
}

// 发送消息
function sendMessage() {
  if (!ws) return;

  switch (Object.prototype.toString.call(_data)) {
    case "[object Object]":
      ws.send(JSON.stringify(_data));
      break;
    case "[object String]":
      ws.send(_data);
  }
}

// 重连尝试
function reconnect() {
  if (reconnectTimer) {
    clearTimeout(reconnectTimer);
  }
  reconnectTimer = setTimeout(() => {
    reconnectNum++;
    webSocket(_url, _data, _callback);
  }, reconnectTime);
}
2、示例(Home.vue)
javascript 复制代码
<template>
  <div class="home">
  </div>
</template>

<script>
// webSocket
import { webSocket } from "@/utils/WebSocket";
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {};
  },
  computed: {},
  created() {},
  mounted() {
    this.initWs();
  },
  methods: {
    initWs() {
      webSocket("ws://192.168.0.1:9999/new", "", this.wsCallBack)
    },
    
    wsCallBack(data){
      console.log("webSocket数据", data)
    }
  },
};
</script>

<style lang="less" scoped>
.home {
  width: 100%;
  height: 100vh;
}
</style>
相关推荐
vx_bisheyuange1 小时前
基于SpringBoot的青年公寓服务平台
前端·vue.js·spring boot·毕业设计
奶糖 肥晨1 小时前
JS自动检测用户国家并显示电话前缀教程|vue uniapp react可用
javascript·vue.js·uni-app
文艺理科生2 小时前
Google A2UI 解读:当 AI 不再只是陪聊,而是开始画界面
前端·vue.js·人工智能
晴栀ay2 小时前
React性能优化三剑客:useMemo、memo与useCallback
前端·javascript·react.js
2501_921649492 小时前
股指期货 API 入门指南:如何获取实时行情与构建交易系统
python·websocket·金融·区块链·restful
json{shen:"jing"}2 小时前
08_组件基础
前端·javascript·vue.js
Bigger3 小时前
Tauri (25)——消除搜索列表默认选中的 UI 闪动
前端·react.js·weui
hongkid3 小时前
React Native 如何打包正式apk
javascript·react native·react.js
aka_tombcato3 小时前
【开源自荐】 AI Selector:一款通用 AI 配置组件,让你的应用快速接入 20+ LLM AI厂商
前端·vue.js·人工智能·react.js·开源·ai编程
七夜zippoe3 小时前
异步编程实战:构建高性能Python网络应用
开发语言·python·websocket·asyncio·aiohttp