vue-封装axios请求

超、凢脫俗 2023-07-25 08:43 163阅读 0赞

最近接手新的vue项目,发现axios竟然没有封装,立马动手封装,这里记录一下完整的封装过程,废话不说,直接上代码
baseConfig.js文件

  1. //存放各个服务器的地址
  2. // const express = require('express')
  3. const proEnv = require('./pro.env') // 生产环境配置文件,这里给出一个示例,其他都相似
  4. const uatEnv = require('./uat.env') // 测试环境
  5. const devEnv = require('./dev.env') // 本地环境
  6. // const app = express()
  7. const env = process.env.NODE_ENV;
  8. console.log("env",env)
  9. let target = '';
  10. if (env === 'development') {
  11. target = devEnv.hosturl
  12. } else if (env === 'production') {
  13. target = proEnv.hosturl
  14. } else {
  15. target = uatEnv.hosturl
  16. }
  17. // module.exports = target
  18. export default target;

pro.env文件

  1. // 生产环境
  2. const hosturl = 'http://xx.xx.xx.xxx:xx'
  3. module.exports = {
  4. NODE_ENV: 'production',
  5. hosturl: hosturl
  6. }

在src/api下新建一个httplib.js来放封装内容

  1. import axios from 'axios'
  2. import {
  3. stringify
  4. } from "qs";
  5. // 引入上述文件
  6. import target from "../config/baseConfig.js";
  7. /*
  8. * 封装axios 2020.4.7 --by lhg
  9. */
  10. const codeMessage = {
  11. 200: "服务器成功返回请求的数据。",
  12. 201: "新建或修改数据成功。",
  13. 202: "一个请求已经进入后台排队(异步任务)。",
  14. 204: "删除数据成功。",
  15. 400: "发出的请求有错误,服务器没有进行新建或修改数据的操作。",
  16. 401: "用户没有权限(令牌、用户名、密码错误)。",
  17. 403: "用户得到授权,但是访问是被禁止的。",
  18. 404: "发出的请求针对的是不存在的记录,服务器没有进行操作。",
  19. 406: "请求的格式不可得。",
  20. 408: "请求失败了",
  21. 410: "请求的资源被永久删除,且不会再得到的。",
  22. 422: "当创建一个对象时,发生一个验证错误。",
  23. 500: "服务器发生错误,请检查服务器。",
  24. 502: "网关错误。",
  25. 503: "服务不可用,服务器暂时过载或维护。",
  26. 504: "网关超时。"
  27. };
  28. const getFullUrl = (url) => {
  29. if (url.indexOf("http://") != -1 || url.indexOf("https://") != -1) {
  30. return url;
  31. }
  32. let newUrl = target + url;
  33. return newUrl;
  34. }
  35. //todo:暂时不了解返回数据结构,可根据自己项目的返回数据格式进行编写 2020.4.7
  36. // const checkStatus = response => {
  37. // // console.log("checkStatus respone = ", response);
  38. // // if (response.status >= 200 && response.status < 300) {
  39. // // // token失效处理
  40. // // if (response.data && response.data.result == 9 ||response.data.result == 104 || response.data.result == 105 || response.data.result == 1007) {
  41. // // store.dispatch('user/resetToken').then(() => {
  42. // // setTimeout(() => {
  43. // // location.reload();
  44. // // }, 1000);
  45. // // });
  46. // // }
  47. // // return response;
  48. // // }
  49. // const errortext = codeMessage[response.status] || response.statusText;
  50. // const error = new Error(errortext);
  51. // error.name = response.status;
  52. // error.response = response;
  53. // throw error;
  54. // };
  55. /**
  56. * 执行 post 请求, 请求体为 JSON
  57. * @param {JSON} requestConfig 请求参数
  58. * {
  59. * url:"/view/a/b/xxxxx",
  60. * params: {
  61. * var1:"var1"
  62. * ...
  63. * },
  64. * headers: {}, // headers
  65. * timeout: 15000, //超时时长,单位毫秒
  66. * config:{ // axios config
  67. * ...
  68. * }
  69. * }
  70. */
  71. export function postJson(requestConfig) {
  72. // console.log("postForm , body = ", requestConfig.params);
  73. const options = {
  74. url: getFullUrl(requestConfig.url),
  75. method: "post",
  76. data: requestConfig.params, //将对象转换为JSON字符串
  77. headers: requestConfig.headers || {
  78. "Content-Type": "application/json; charset=utf-8"
  79. },
  80. };
  81. // alert(JSON.stringify(options));
  82. return request(options);
  83. }
  84. /**
  85. * 执行 post from表单 请求, 请求方式为 form 表单提交
  86. * @param {JSON} requestConfig 请求参数
  87. *
  88. */
  89. export function postForm(requestConfig) {
  90. console.debug("调用 postForm , url = ", getFullUrl(requestConfig.url));
  91. const dataParams = stringify(requestConfig.params); //将对象转换为 key1=val1&key2=val2 格式
  92. // console.debug("body, data = ", dataParams);
  93. const options = {
  94. method: "post",
  95. data: dataParams,
  96. headers: requestConfig.headers || {
  97. Accept: "application/json",
  98. "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
  99. },
  100. url: getFullUrl(requestConfig.url),
  101. };
  102. return request(options);
  103. }
  104. /**
  105. * 执行 get 请求
  106. * @param {JSON} requestConfig 请求参数
  107. *
  108. */
  109. export function get(requestConfig) {
  110. const options = {
  111. method: "get",
  112. headers: requestConfig.headers || {
  113. Accept: "application/json"
  114. // "Content-Type": "application/json"
  115. },
  116. params: requestConfig.params,
  117. url: getFullUrl(requestConfig.url),
  118. // timeout: requestConfig.timeout || 15000
  119. };
  120. return request(options);
  121. }
  122. /**
  123. * Requests a URL, returning a promise.
  124. *
  125. * @param {object} [option] The options we want to pass to "axios.request"
  126. * @return {object} An object containing either "data" or "err"
  127. */
  128. export function request(option) {
  129. // console.log(option);
  130. // console.log("request url = %s, params = %o", option.url, option.data);
  131. const options = {
  132. ...option
  133. };
  134. const defaultOptions = {
  135. // credentials: 'include',
  136. timeout: 15000
  137. };
  138. const newOptions = {
  139. ...defaultOptions,
  140. ...options
  141. };
  142. return (
  143. axios
  144. .request(newOptions)
  145. // .then(checkStatus)
  146. .then(response => {
  147. // alert(response)
  148. console.log('response:', response);
  149. return response.data;
  150. // }).then(response => {
  151. // return response;
  152. }).catch(error => {
  153. console.log("request error = ", error);
  154. if (error.response) {
  155. // The request was made and the server responded with a status code
  156. // that falls out of the range of 2xx
  157. console.log("error.response.data = ", error.response.data);
  158. console.log("error.response.status = ", error.response.status);
  159. console.log("error.response.headers = ", error.response.headers);
  160. } else if (error.request) {
  161. // The request was made but no response was received
  162. // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
  163. // http.ClientRequest in node.js
  164. console.log("error.request = ", error.request);
  165. } else {
  166. // Something happened in setting up the request that triggered an Error
  167. console.log("error.message = ", error.message);
  168. }
  169. console.log("error.config = ", error.config);
  170. })
  171. );
  172. }

至此,封装完成,下面是在组件中调用示例
在src/api下面统一管理接口,可根据不同的组件建立文件夹

  1. import {get, postForm, postJson} from '../httplib'
  2. //测试axios封装
  3. export function test_axios() {
  4. return postJson({
  5. params: {
  6. "account": "254745674567",
  7. "password": "976e3af6173e0939c642ea003e4cb956",
  8. "platform": 3,
  9. "device": {
  10. "udid": "254745674567"
  11. }
  12. },
  13. url: "/api/center/login"
  14. })
  15. }

在组件中调用

  1. <template>
  2. <div>
  3. 测试
  4. </div>
  5. </template>
  6. <script>
  7. import { test_axios} from '@/api/dataview/dataview'
  8. export default {
  9. mounted() {
  10. const res = test_axios()
  11. console.log("res", res);
  12. }
  13. }
  14. </script>

最后,记录一个小问题,小伙伴们要注意module.exports、require和export default、import要配对使用哦,不可混用,因为之前代码遗留为module.exports,而我使用import导入,所以一直报错

发表评论

表情:
评论列表 (有 0 条评论,163人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Vue中统一封装Axios请求

    1.Axios 是什么,为什么要统一封装? axios是一个基于promise的http库,可运行在浏览器端和node.js中。他有很多优秀的特性,例如统一进行拦截请...

    相关 vue-封装axios请求

    最近接手新的vue项目,发现axios竟然没有封装,立马动手封装,这里记录一下完整的封装过程,废话不说,直接上代码 baseConfig.js文件 //存放各个服