当前位置:   article > 正文

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

vue taro 中请求封装

一、Axios

1、Axios封装(request.js)
  1. import axios from "axios";
  2. // 开发环境配置
  3. const baseURL = "/api";
  4. // 生产环境配置
  5. // const baseURL = 'http://192.168.0.1:9000'
  6. // 创建axios实例
  7. const http = axios.create({
  8. baseURL: baseURL,
  9. timeout: 5000, // 超时时间
  10. });
  11. // 设置默认请求数据格式
  12. http.defaults.headers.post["Content-Type"] = "application/json;charset=utf-8";
  13. // 请求拦截
  14. http.interceptors.request.use(
  15. (request) => {
  16. return request;
  17. },
  18. (error) => {
  19. return error;
  20. }
  21. );
  22. // 响应拦截
  23. http.interceptors.response.use(
  24. (response) => {
  25. return response.data;
  26. },
  27. (error) => {
  28. return error;
  29. }
  30. );
  31. export default http;

2、示例(api.js)
  1. import http from './request'
  2. // get请求(params = {})
  3. function getRequest(params) {
  4. return http.get(`/api?user=${params.user}&passwd=${params.passwd}`)
  5. }
  6. // post请求(params = {})
  7. function postRequest(params) {
  8. return http.post('/api', params)
  9. }
  10. // put请求(params = {})
  11. function putRequest(params) {
  12. return http.put('/api', params)
  13. }
  14. // delete请求(params = {})
  15. function deleteRequest(params) {
  16. return http.delete('/api', {
  17. data:params
  18. })
  19. }
  20. export default {
  21. getRequest,
  22. postRequest,
  23. putRequest,
  24. deleteRequest
  25. }

二、WebSocket

1、Ws封装(WebSocket.js)
  1. let ws = null;
  2. let _data = null;
  3. let _url = null;
  4. let _callback = null;
  5. let hearBeatTimer = null;
  6. let reconnectTimer = null;
  7. let reconnectNum = 0; // 重连次数
  8. const time = 3000; // 心跳间隔
  9. const reconnectTime = 5000; // 重连超时
  10. // 初始化
  11. export function webSocket(url = "", data = "", callback = () => { }) {
  12. _url = url; // 地址
  13. _data = data; // 发送消息
  14. _callback = callback; // 回调函数,利用闭包
  15. createWebSocket(); // 创建 webSocket
  16. }
  17. // 获取连接
  18. export function getWebSocket() {
  19. return ws;
  20. }
  21. // 创建连接
  22. function createWebSocket() {
  23. if (!_url) return;
  24. if (ws) {
  25. ws.close();
  26. ws = null;
  27. }
  28. ws = new WebSocket(_url);
  29. ws.onopen = function () {
  30. sendMessage();
  31. heartBeat();
  32. };
  33. ws.onmessage = function (e) {
  34. if (typeof _callback === "function") {
  35. _callback(e);
  36. }
  37. reconnectNum = 0;
  38. heartBeat();
  39. };
  40. ws.onerror = function () {
  41. // console.log('链接失败,正在重连');
  42. reconnect();
  43. };
  44. ws.onclose = function () {
  45. reconnect();
  46. };
  47. }
  48. // 关闭连接
  49. export function closeWebSocket() {
  50. if (ws) {
  51. ws.onerror = () => { };
  52. ws.onclose = () => { };
  53. ws.close();
  54. }
  55. ws = null;
  56. _data = null;
  57. _url = null;
  58. _callback = () => { };
  59. hearBeatTimer = null;
  60. reconnectTimer = null;
  61. }
  62. // 心跳检测
  63. function heartBeat() {
  64. if (hearBeatTimer) {
  65. clearTimeout(hearBeatTimer);
  66. }
  67. hearBeatTimer = setTimeout(() => {
  68. // console.log("ws连接状态:", ws.readyState);
  69. if (ws && ws.readyState < 2) {
  70. // 如果连接正常
  71. sendMessage();
  72. } else {
  73. reconnect();
  74. }
  75. }, time);
  76. }
  77. // 发送消息
  78. function sendMessage() {
  79. if (!ws) return;
  80. switch (Object.prototype.toString.call(_data)) {
  81. case "[object Object]":
  82. ws.send(JSON.stringify(_data));
  83. break;
  84. case "[object String]":
  85. ws.send(_data);
  86. }
  87. }
  88. // 重连尝试
  89. function reconnect() {
  90. if (reconnectTimer) {
  91. clearTimeout(reconnectTimer);
  92. }
  93. reconnectTimer = setTimeout(() => {
  94. reconnectNum++;
  95. webSocket(_url, _data, _callback);
  96. }, reconnectTime);
  97. }

2、示例(Home.vue)
  1. <template>
  2. <div class="home">
  3. </div>
  4. </template>
  5. <script>
  6. // webSocket
  7. import { webSocket } from "@/utils/WebSocket";
  8. export default {
  9. name: "",
  10. components: {},
  11. props: {},
  12. data() {
  13. return {};
  14. },
  15. computed: {},
  16. created() {},
  17. mounted() {
  18. this.initWs();
  19. },
  20. methods: {
  21. initWs() {
  22. webSocket("ws://192.168.0.1:9999/new", "", this.wsCallBack)
  23. },
  24. wsCallBack(data){
  25. console.log("webSocket数据", data)
  26. }
  27. },
  28. };
  29. </script>
  30. <style lang="less" scoped>
  31. .home {
  32. width: 100%;
  33. height: 100vh;
  34. }
  35. </style>

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号