基于axios的网络封装

一、安装axios
利用npm安装npm install axios --save
axios入门参考

二、新建一个js文件


基于axios的网络封装_第1张图片
image.png

命名为axios-http.js,代码如下

//声明:不同的后台有不同的请求方式,我们的格式 【http://url路径?action="方法名"&jsonString="加密参数集"】
'use strict';
import axios from 'axios'

//默认参数配置
let Method = "GET";
let TimeOut = 30000;
let DataType = "json";
let tokenUserId = 2;
let token = "186f5a12ff9d6563efcc61169d2bc894";
let ContentType = "application/x-www-form-urlencoded;charset=utf-8";
axios.defaults.baseURL = 'http://api-scf-test.xcsqjr.com/api?action='; //请求的API
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

axios.interceptors.request.use(config => {    // 这里的config包含每次请求的内容
  // 判断localStorage中是否存在api_token
  if (localStorage.getItem('api_token')) {
    //  存在将api_token写入 request header
    config.headers.apiToken = `${localStorage.getItem('api_token')}`;
  }
  return config;
}, err => {
  return Promise.reject(err);
});

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
});

//成功返回
function isSuccess(response) {
  // 如果http状态码正常,则直接返回数据
  if (response && (response.code === 200 || response.isSuccess === true)) {
    return response
  }
  // 异常状态下,把错误信息返回去
  return response
}

//失败返回
function error(res) {
  if (res.data && (!res.data.success)) {
    return res.data;
  }
}

// 请求方式的配置
export default {
  /**
   * 网络加载
   * @param options
   * @returns {Promise>}
   */
  doAjax(options) {  // get
    //默认配置
    let params = {"tokenUserId": tokenUserId, "token": token};
    params["rand"] = new Date().toLocaleTimeString();

    //1.加载
    let Base64 = require("js-base64").Base64;  //require获取Base64
    let jq = require("jquery"); //加载jquery

    let cache = options.cache;
    if (cache == false || cache == undefined) {
      params = jq.extend({cache: false}, params);
    }

    //2.转化
    let data = options.data;
    if (data == undefined) {
      data = {};
    }
    let jsonString = JSON.stringify(jq.extend(data, params));

    //3.加密
    let reqData = {jsonString: Base64.encode(jsonString)};

    //打印地址
    console.log("请求信息:" + JSON.stringify(axios.defaults.baseURL + options.action + "&jsonString=" + Base64.encode(jsonString)));

    //4.请求
    return axios({
      params: reqData,
      method: options.type || Method,
      timeout: options.timeout || TimeOut,
      dataType: options.dataType || DataType,
      url: axios.defaults.baseURL + options.action,
      contentType: options.contentType || ContentType,
    }).then(
      (response) => {
        //成功
        return isSuccess(response)
      }
    ).then(
      (res) => {
        //失败
        return error(res)
      }
    )
  }
}

三、在main.js中注册

import Vue from 'vue'
import App from './App'
import Axios from './common/net/axios-http';//网络请求

Vue.prototype.$Axios = Axios;

四、方法使用

//以下是个登录方法
···
methods: {
      validateSubmit(name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            // this.$Message.success('Success!');
            // setTimeout(() => {
            //   this.$store.state.user = {test: "test"}
            //   this.$router.push({path: '/main'})
            // }, 2000)

            this.$Axios.doAjax({
              action: 'userService.login',
              data: {
                name: this.$refs.username.value,
                password: this.$refs.password.value,
                systemSourceId: this.CONSTANT.systemSourceId,
              },
              type: 'get'
            }).then((response) => {
              let data = response;
              if (data.isSuccess) {
                this.$store.state.user = data.data;
                this.$Message.success('Success!');
                this.$router.push({path: '/main'})
                console.log(data);
              } else {
                this.$Message.error(data.description);
              }
            }).catch(function (err) {
              console.log(err)
            });
          }
        })
      }

你可能感兴趣的:(基于axios的网络封装)