vue请求类的封装,基于jQuery版本和Axios,两个版本

8 篇文章 0 订阅
3 篇文章 0 订阅
vue中基于jQuery请求类的封装:
 
/**  * 该插件基于JQuery的基础封装的,使用的时请自配JQuery  * 使用方法:在页面import该JS文件  * XXX.post({··parameter··}).then((response) =>{ success })  */ import Vue from 'vue' import store from '../store' import router from '../router' import message from '../components/toast/message'  let Export = {} let vue = new Vue({router}) Export.post = function (options) { options.method = 'POST'  return Request(options) } Export.get = function (options) { options.method = 'GET'  return Request(options) } Export.put = function (options) { options.method = 'PUT'  return Request(options) } Export.del = function (options) { options.method = 'DELETE'  return Request(options) } const Request = function (options) { let newDef = $.Deferred() store.dispatch('showloader') /**  * @url:请求的接口地址  * @method: 请求方式(GET/POST/PUT/DELETE)  * @param: 请求参数{key:val} (id:'11',name:'name')  * @headers: 请求的headers{key:val} (token:aabbccdd)  * @useCache: 缓存(针对GET方式)  * @skipValidation:跳过验证  */  let url = vue.SERVER_NAME + vue.API_PREFIX + options.url  let method = options.method  let param = options.data || true  let headers = options.headers || true  let useCache = options.cache || true  let skipValidation = !!options.skipValidation;  if (method !== "GET") { param = (typeof param === "string") ? param : JSON.stringify(param) } $.ajax({ url: url,  type: method.toUpperCase(),  dataType: "json",  contentType: "application/json; charset=utf-8",  headers: headers,  data: param,  cache: !!useCache,  success: (data) => { if (skipValidation) { newDef.resolve(data) } else if (handleApiResponseStatus(url, data)) { newDef.resolve(data) } },  error:(request, textStatus) => { handleHttpResponseStatus(url, request.status) } });  /**  * 处理接口响应状态  */  function handleApiResponseStatus(url, data){ console.info('handle Api Response Status Error') if (!data || (!data.codeText)) { console.error(url, data) return false  } if (data.codeText == "RESULT_LOGIN_EXPIRED") { console.info('哎呦喂!登陆超时') message.msg('哎呦喂!登陆超时') return false  } else if (data.codeText == "RESULT_NEED_ADVANCE_AUTH") { console.info('哎呦喂!登陆超时,重新登陆') } else if (data.codeText == "RESULT_NEED_BINDPHONE") { return true  } else if (data.codeText == "FORBIDDEN") { console.info('哎呦喂!权限验证失败') return false  } return true  } /**  * 处理HTTP相应状态  */  function handleHttpResponseStatus(url, status) { console.info('handle Http Response Status Error:' + status) let statu = Number(status) if (statu == 404) { console.info('哎呦喂!我找不到页面') message.msg('哎呦喂!我找不到页面') } else if (statu >= 500) { console.info('哎呦喂!服务器异常') console.info('哎呦喂!服务器异常') } else { console.info('哎呦喂!网络出现异常') console.info('哎呦喂!网络出现异常') } } store.dispatch('hideloader') return newDef.promise() } export default Export 

 

----------------------------------------------------------------------------------------

 

 
 
/**  * 该工具类基于axios,请自行安装axios和qs  * npm install axios  * npm install qs  * 该工具类借鉴之前看的一篇博客,后期使用过程中做后续优化  * store是状态管理,这里操作loading,不需要的可删除  */

 

import Vue from 'vue'
import Axios from 'axios'
import Qs from 'qs'
import router from '../router'
import store from '../store'

let vue = new Vue({router})
//请求
Axios.interceptors.request.use( config => {
  store.commit('updateLoading', true)
 return config
}, error => {
  return Promise.reject(error)
})
//请求返回
Axios.interceptors.response.use( response => {
  return response
}, error => {
  return Promise.reject(error.response)
})
//http请求
const Request = (options) => {
  //默认配置项
  let defaultOptions = {
    method: options.method,
    baseURL: vue.SERVER_NAME + vue.API_PREFIX,
    url: options.url,
    timeout: 3000,
    params: Object.assign(options.data),
    data: Qs.stringify(Object.assign(options.data)),
    headers: options.method == 'get' ? {
      'X-Requested-With': 'XMLHttpRequest',
      "Accept": "application/json",
      "Content-Type": "application/json; charset=UTF-8"
    }:{
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
  }
  //对get or !get请求处理
  if(options.method == 'get'){
    delete  defaultOptions.data
  } else {
    delete defaultOptions.params
  }

  let promise = new Promise(function (resolve, reject) {
    Axios(defaultOptions).then( (response) =>{
      if (handleApiResponseStatus(response))
      resolve(response.data)
    }).catch((response) => {
      if(handleHttpResponseStatus(response))
      reject(response)
    })
  })
  return promise
}
//处理Http响应状态
function handleHttpResponseStatus(response) {
  store.commit('updateLoading', false)
}
//处理Api响应状态
function handleApiResponseStatus(response) {
  store.commit('updateLoading', false)
}

export default Request

 

//  反向代理  config/index.js

proxyTable: {
    '/api': {    //将www.exaple.com印射为/apis
        target: 'http:',  // 接口域名
        secure: false,  // 如果是https接口,需要配置这个参数
        changeOrigin: true,  //是否跨域
        pathRewrite: {
            '^/api': ''   //需要rewrite的,
        }              
    }
},

使用:

axios.get('http://localhost:xxxx/api/artemis/basicvideo/ptz'
点击链接加入群【ng-vue】:https://jq.qq.com/?_wv=1027&k=52pOebh

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值