当前位置:   article > 正文

vue项目中的http.js(请求封装)_vue http.js

vue http.js

第一个版本和第二个版本,感觉还行啊

第一个版本 

vue+vant 

  1. import axios from 'axios'
  2. import { Toast } from 'vant';
  3. import store from '@/store/index.js'
  4. import router from '@/router'
  5. import {
  6. getToken
  7. } from '@/libs/util'
  8. const instance = axios.create({
  9. timeout: 105000,
  10. headers: {
  11. 'Content-Type': 'application/json; charset=utf-8'
  12. }
  13. })
  14. /**
  15. * 请求拦截
  16. */
  17. instance.interceptors.request.use(async config => {
  18. if (getToken()) {
  19. // 如果是CAS平台
  20. // 在请求头部增加 切换的租户 字段(User-Information)发给后台
  21. config.headers.Authorization = getToken()
  22. // request.headers['Tenant_id'] = getCurrentTenantId()
  23. config.headers['Tenant-ID'] = localStorage.getItem('tenantId')
  24. if (config.url.indexOf('login') === -1 && config.url.indexOf('refreshToken') === -1 && config.url.indexOf('selectUnReadMessage') === -1) {
  25. await store.dispatch('refreshToken')
  26. }
  27. }
  28. return config
  29. }, error => {
  30. return Promise.reject(error)
  31. })
  32. /**
  33. * 响应拦截
  34. */
  35. instance.interceptors.response.use(response => {
  36. if ((response.data.code === 'E0B00001' && response.data.data === 'E0B00002') || response.data.code == 401) {
  37. //Toast(response.data.msg);
  38. return router.replace({
  39. name: 'transfer',
  40. })
  41. }
  42. return Promise.resolve(response)
  43. }, error => {
  44. if (error.response.status === 500 || error.response.status === 502) {
  45. Toast(error.response.data.msg);
  46. } else if (error.response.status == 401) {
  47. //token失效
  48. Toast(error.response.data.msg);
  49. router.replace({
  50. name: 'transfer',
  51. })
  52. } else if (error.response.status === 404) {
  53. Toast('请求接口不存在' + error.response.status);
  54. } else {
  55. Toast(error.response.status);
  56. }
  57. return Promise.reject(error)
  58. })
  59. const http = {
  60. get: (path, data, config) =>
  61. instance.get(path, {
  62. params: data,
  63. ...config
  64. }),
  65. post: (path, data, config) => instance.post(path, data, config),
  66. put: (path, data, config) => instance.put(path, data, config),
  67. delete: (path, data, config) =>
  68. instance.delete(path, {
  69. data,
  70. ...config
  71. })
  72. }
  73. export default http

第二个版本 

vue+element-ui 

  1. /*
  2. * @Author: 梁观晖
  3. * @Date: 2019-07-12 13:39:15
  4. * @LastEditors: MoMaek 杨兴
  5. * @LastEditTime: 2021-01-15 16:14:40
  6. * @Description: no description
  7. */
  8. import axios from 'axios'
  9. import router from '@/router'
  10. import {
  11. getToken
  12. } from '@/libs/util'
  13. // 2021年6月22日:统一ui框架为elementUI
  14. import {
  15. Message,
  16. Loading
  17. } from 'element-ui';
  18. import store from '@/store/index.js'
  19. // import { mapActions, mapState } from 'vuex'
  20. const instance = axios.create({
  21. // baseURL: baseUrl,
  22. timeout: 105000,
  23. // withCredentials: true,
  24. headers: {
  25. 'Content-Type': 'application/json; charset=utf-8'
  26. }
  27. })
  28. let loadingInstance = null; // 记录页面中存在的loading
  29. let loadingCount = 0; // 记录当前正在请求的数量
  30. function showLoading(data) {
  31. if (loadingCount === 0) {
  32. loadingInstance = Loading.service({
  33. lock: true,
  34. text: data || '加载中……'
  35. });
  36. }
  37. loadingCount++
  38. };
  39. function hideLoading() {
  40. loadingCount--
  41. if (loadingInstance && loadingCount === 0) {
  42. loadingInstance.close()
  43. loadingInstance = null
  44. }
  45. }
  46. // 这里的response包含每次请求的内容
  47. instance.interceptors.request.use(
  48. async request => {
  49. if (!request.loadingHide) {
  50. showLoading(request.loadingText)
  51. }
  52. // 全局给header添加token
  53. if (getToken()) {
  54. // 如果是CAS平台
  55. // 在请求头部增加 切换的租户 字段(User-Information)发给后台
  56. request.headers.Authorization = getToken()
  57. // request.headers['Tenant_id'] = getCurrentTenantId()
  58. request.headers['Tenant-ID'] = localStorage.getItem('tenantId')
  59. if (request.url.indexOf('login') === -1 && request.url.indexOf('refreshToken') === -1 && request.url.indexOf('selectUnReadMessage') === -1) {
  60. await store.dispatch('refreshToken')
  61. }
  62. }
  63. return request
  64. },
  65. error => {
  66. return Promise.reject(error)
  67. }
  68. )
  69. // 拦截器
  70. instance.interceptors.response.use(
  71. (response) => {
  72. if (!response.config.loadingHide) {
  73. hideLoading()
  74. }
  75. // paas token失效
  76. // || response.data.code == 401
  77. if (response.data.code === 'E0B00001' && response.data.data === 'E0B00002') {
  78. Message({
  79. message: response.data.msg,
  80. type: 'warning'
  81. });
  82. let timer = setTimeout(() => {
  83. router.replace({
  84. name: 'login',
  85. params: {
  86. clear: true
  87. }
  88. })
  89. clearTimeout(timer)
  90. }, 1000)
  91. return
  92. }
  93. return response
  94. },
  95. (error) => {
  96. if (!error.config.loadingHide) {
  97. hideLoading()
  98. }
  99. if (error.response.status === 500 || error.response.status === 502) {
  100. Message({
  101. message: error.response.data.msg,
  102. type: 'warning'
  103. });
  104. } else if (error.response.status === 404) {
  105. Message({
  106. message: '请求接口不存在' + error.response.status,
  107. type: 'error'
  108. });
  109. } else if (error.response.status === 401) {
  110. Message({
  111. message: 'token失效,请重新登陆',
  112. type: 'warning'
  113. });
  114. router.replace({
  115. name: 'login',
  116. params: {
  117. clear: true
  118. }
  119. })
  120. } else {
  121. Message({
  122. message: error.response.status,
  123. type: 'warning'
  124. });
  125. }
  126. return Promise.reject(error)
  127. }
  128. )
  129. const http = {
  130. get: (path, data, config) =>
  131. instance.get(path, {
  132. params: data,
  133. ...config
  134. }),
  135. post: (path, data, config) => instance.post(path, data, config),
  136. put: (path, data, config) => instance.put(path, data, config),
  137. delete: (path, data, config) =>
  138. instance.delete(path, {
  139. data,
  140. ...config
  141. })
  142. }
  143. export default http

第一个版本和第二个版本的使用,都是一样的,如下: 

 使用

①main.js中引用

  1. //main.js
  2. import http from "@/libs/request";
  3. Vue.prototype.$http = http;

②vue文件中使用

  1. <template>
  2. <div id="app">
  3. <router-view></router-view>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name: 'app',
  9. components: {
  10. },
  11. created() {
  12. this.$http.post("/cmdb-base/instanceAsst/findAllInstanceAsstListApp", this.dataForm).then(({ data: res }) => {
  13. if (res.code != "S1A00000") {
  14. this.groupList = []
  15. return this.$toast.fail(res.msg)
  16. }
  17. this.groupList = res.data || []
  18. }).finally(() => {
  19. this.dataLoading = false
  20. })
  21. }
  22. }
  23. </script>
  24. <style>
  25. </style>

 ③ 其他js中的使用,比如vuex的store.js

  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. import HTTP from '@/libs/request'
  4. import sysConfig from './module/sysConfig'
  5. import {
  6. setToken
  7. } from '@/libs/util'
  8. Vue.use(Vuex)
  9. export default new Vuex.Store({
  10. state: {
  11. },
  12. getters: {
  13. },
  14. mutations: {
  15. },
  16. actions: {
  17. handleNewLogin({
  18. state,
  19. commit
  20. }, {
  21. type,
  22. appSessionKey,
  23. account,
  24. pwd,
  25. userType
  26. }) {
  27. return new Promise((resolve) => {
  28. let url = ""
  29. let method = ""
  30. let params = null
  31. if (type === 'local') {
  32. url = '/cmdb-rbac/v1/sysLogin/login'
  33. method = 'post'
  34. params = {
  35. account: account.trim(),
  36. pwd: pwd,
  37. userType
  38. }
  39. } else {
  40. url = '/base-auth/oauth/login'
  41. method = 'get'
  42. params = {
  43. [state.sysConfig.sso.appSessionKey]: appSessionKey,
  44. // [state.sysConfig.sso.redirectKey]: state.sysConfig.sso.redirectValue
  45. }
  46. }
  47. HTTP[method](url, params).then(({ data: res }) => {
  48. if (res.code !== 'S1A00000') {
  49. resolve(res)
  50. return
  51. }
  52. setToken(res.data.token)
  53. localStorage.setItem('tenantId', res.data.userInfo.user.tenantId)
  54. localStorage.setItem('expireTime', res.data.expireTime)
  55. resolve(res)
  56. })
  57. .catch((err) => {
  58. resolve({
  59. code: 'E0B00001',
  60. 'msg': err.message
  61. })
  62. }).finally(() => {
  63. })
  64. })
  65. },
  66. },
  67. modules: {
  68. sysConfig
  69. }
  70. // plugins: [persistedState()]
  71. })

第三个版本

  1. import axios from 'axios'
  2. import { message } from 'ant-design-vue'
  3. import Cookie from 'js-cookie'
  4. let isFormData = (v) => {
  5. return Object.prototype.toString.call(v) === '[object FormData]';
  6. }
  7. axios.defaults.timeout = 10000
  8. // axios.defaults.withCredentials = true
  9. axios.defaults.crossDomain = true
  10. let sessions = {}
  11. //http request 拦截器
  12. axios.interceptors.request.use(
  13. config => {
  14. if (!isFormData(config.data)) {
  15. config.data = JSON.stringify(config.data)
  16. }
  17. const jwt = Cookie.get('jwt');
  18. const sessions = Cookie.get('sessions') ? JSON.parse(Cookie.get('sessions')) : {}
  19. // 判断是否是登录请求
  20. // true
  21. if (config.url.indexOf('admin-user/login') > -1) {
  22. config.headers = {
  23. 'Content-Type': 'application/json;charset=UTF-8',
  24. }
  25. } else {
  26. // false
  27. // 判断是否有登录token
  28. if (jwt) {
  29. if (isFormData(config.data)) {
  30. config.headers = {
  31. "Content-Type": "multipart/form-data",
  32. 'Authorization': jwt,
  33. ...sessions
  34. }
  35. } else {
  36. config.headers = {
  37. 'Content-Type': 'application/json;charset=UTF-8',
  38. 'Authorization': jwt,
  39. ...sessions
  40. }
  41. }
  42. } else {
  43. if (isFormData(config.data)) {
  44. config.headers = {
  45. "Content-Type": "multipart/form-data",
  46. ...sessions
  47. }
  48. } else {
  49. config.headers = {
  50. 'Content-Type': 'application/json;charset=UTF-8',
  51. ...sessions
  52. }
  53. }
  54. }
  55. }
  56. return config;
  57. },
  58. error => {
  59. return Promise.reject(error);
  60. }
  61. )
  62. //http response 拦截器
  63. axios.interceptors.response.use(
  64. response => {
  65. // console.log('success',response)
  66. response.headers.Authorization && Cookie.set('jwt', 'Bearer ' + response.headers.Authorization, { expires: 7 })
  67. return response;
  68. },
  69. err => {
  70. console.log('fail', err.response)
  71. console.log('fail', err)
  72. if (err && err.response) {
  73. switch (err.response.status) {
  74. case 400:
  75. err.message = '请求错误'
  76. break
  77. case 401:
  78. break
  79. case 403:
  80. err.message = '登录过期,请重新登录'
  81. break
  82. case 404:
  83. err.message = '网络请求不存在'
  84. break
  85. case 408:
  86. break
  87. case 500:
  88. err.message = '请求错误'
  89. break
  90. case 501:
  91. err.message = '服务未实现'
  92. break
  93. case 502:
  94. err.message = '网关错误'
  95. break
  96. case 503:
  97. err.message = '服务不可用'
  98. break
  99. case 504:
  100. err.message = '网关超时'
  101. break
  102. case 505:
  103. err.message = 'HTTP版本不受支持'
  104. break
  105. default:
  106. }
  107. } else {
  108. err.message = '网络出现问题,请稍后再试'
  109. }
  110. message.error(err.message);
  111. return Promise.reject(err)
  112. }
  113. )
  114. /**
  115. * get请求
  116. * @param url
  117. * @param params
  118. * @returns {Promise}
  119. */
  120. export function get(url, params = {}) {
  121. sessions = Cookie.get('sessions') ? JSON.parse(Cookie.get('sessions')) : {}
  122. return new Promise((resolve, reject) => {
  123. axios.get(Util.baseUrl + url, {
  124. params: params
  125. })
  126. .then(response => {
  127. // 请求成功
  128. resolve(response.data)
  129. })
  130. .catch(err => {
  131. reject(err)
  132. })
  133. })
  134. }
  135. /**
  136. * post请求
  137. * @param url
  138. * @param data
  139. * @returns {Promise}
  140. */
  141. export function post(url, data = {}) {
  142. return new Promise((resolve, reject) => {
  143. axios.post(Util.baseUrl + url, data)
  144. .then(response => {
  145. // 请求成功
  146. resolve(response.data)
  147. })
  148. .catch(err => {
  149. reject(err)
  150. })
  151. })
  152. }
  153. /**
  154. * post请求 params
  155. * @param url
  156. * @param data
  157. * @returns {Promise}
  158. */
  159. export function postParams(url, params = {}, data = {}) {
  160. return new Promise((resolve, reject) => {
  161. axios({
  162. method: 'post',
  163. url: Util.baseUrl + url,
  164. params: params,
  165. body: data
  166. })
  167. .then(response => {
  168. console.log(response)
  169. // 请求成功
  170. resolve(response.data)
  171. })
  172. .catch(err => {
  173. reject(err)
  174. })
  175. })
  176. }
  177. /**
  178. * 文件上传 uploadFile(使用post请求)
  179. * @param url
  180. * @param data
  181. * @returns {Promise}
  182. * @param 不需要传passportId
  183. *
  184. *$$$$$$参数module取值参考如下$$$$$$$$$
  185. *运营中心服务【租户、秘钥】 【20010】
  186. 'spm-operation'
  187. *统一组织机构服务[组织、部门等] 【20020】
  188. 'spm-org-structure'
  189. *权限管理服务[资源菜单、角色、用户等] 【20030】
  190. 'spm-admin'
  191. *账号信息服务[统一账号、账户管理] 【20040】
  192. 'spm-passport'
  193. *统一鉴权中心服务[Token管理、认证、刷新] 【20050】
  194. 'spm-auth-server'
  195. *应用中心服务[应用注册] 【20060】
  196. 'spm-app-center'
  197. *第三方服务【提供短信、消息推送】 【20070】
  198. 'spm-third-party'
  199. *系统服务(基础数据、版本、服务等) 【20080】
  200. 'spm-system'
  201. *文件服务[文件/图片上传下载/处理等功能] 【20090】
  202. 'spm-file-upload'
  203. *即时通讯信息服务[im管理] 【20100】
  204. 'spm-im'
  205. *日志监控服务logstash 【20110】
  206. 'spm-logstash'
  207. */
  208. export function uploadFile(data = {}) {
  209. return new Promise((resolve, reject) => {
  210. //固定参数
  211. const fixedParams = {
  212. appId: 'spm',
  213. appName: 'spm',
  214. }
  215. //合并参数
  216. let params = { ...fixedParams, ...data }
  217. //创建formData 并赋值
  218. let formData = new FormData();
  219. for (let key in params) {
  220. formData.append(key, params[key])
  221. }
  222. //请求后台
  223. axios({
  224. method: 'post',
  225. url: 'http://39.105.163.75:20090/V1.0.0/api/file/upload',
  226. data: formData,
  227. })
  228. .then(response => {
  229. // 请求成功
  230. resolve(response.data)
  231. })
  232. .catch(err => {
  233. reject(err)
  234. })
  235. })
  236. }
  237. export function uploadImg(data = {}) {
  238. return new Promise((resolve, reject) => {
  239. //请求后台
  240. axios({
  241. method: 'post',
  242. url: 'http://39.105.163.75:20090/V1.0.0/api/file/upload',
  243. data: data,
  244. })
  245. .then(response => {
  246. // 请求成功
  247. resolve(response.data)
  248. })
  249. .catch(err => {
  250. reject(err)
  251. })
  252. })
  253. }
  254. export function exportFile(url, data = {}) {
  255. return new Promise((resolve, reject) => {
  256. axios({
  257. method: "post",
  258. url: Util.baseUrl + url,
  259. data: data,
  260. responseType: 'arraybuffer'
  261. })
  262. .then(response => {
  263. // 请求成功
  264. resolve(response.data)
  265. })
  266. .catch(err => {
  267. reject(err)
  268. })
  269. })
  270. }
  271. /**
  272. * 并发请求
  273. * @param requestLists
  274. * @returns {Promise<any>}
  275. */
  276. export function getAll(requestLists = []) {
  277. let counter = 1 // 请求次数
  278. let maxRequestTimes = 5 // 最大请求次数,因为有可能别个页面就是访问不了,请求多少次也没用- -
  279. let result = [] // 最后的结果
  280. let failedList = []
  281. return new Promise((resolve, reject) => {
  282. axios.all(requestLists)
  283. .then(response => {
  284. result = result.concat(response.filter(i => i)) // filter返回true的时候保留该数组项,因为getDataById的catch里没有给返回值(这里也不需要),这里的resolve里就会有undefined,需要过滤掉
  285. let failedLength = failedList.length
  286. if (failedLength > 0 && counter < maxRequestTimes) { // 如果失败列表里有请求,并且请求次数不超过设定的值,就进行下一次请求,并且打出log
  287. console.log(`第${counter}次请求完成,其中成功${requestLists.length - failedLength}个,失败${failedLength}个,正在进行第${++counter}次请求...`)
  288. getAll(failedList)
  289. failedList = [] // 这里要清空failedList,不然会一直调用。不用担心,下一次请求失败的会在getAll填充到failedList里。
  290. } else { // 表示所有请求都成功了,或者达到了最大请求次数。到这里就可以对result做进一步处理了。
  291. console.log(`请求完成,共请求${counter}次, 其中成功${requestLists.length - failedLength}个,失败${failedLength}个\n`, result)
  292. counter = 1
  293. resolve(response)
  294. }
  295. })
  296. .catch(err => {
  297. reject(err)
  298. })
  299. })
  300. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/548622
推荐阅读
相关标签
  

闽ICP备14008679号