关于async-await:vue项目asyncawait封装axios请求

11次阅读

共计 1451 个字符,预计需要花费 4 分钟才能阅读完成。

装置 axios

npm install axios --save

创立 http.js 文件

import axios from "axios"
/* 申请拦截器 */
axios.interceptors.request.use(
    config => {
        /* 增加 token */
        let token = localstorage.getItem("token") || "";
        if(token){config.headers["token"] = token
        }
        return config;
    },
    error => {return Promise.reject(error)
    }
)

export const http = (url,params,method='GET',type='json') =>{
    /* 设置工夫随机数,解决申请缓存问题 */
    let _t = new Date().getTime();
    if(method == 'GET' || method == 'get'){if(params){params._t = _t}else{params={ _t}
        }
    }
    /* 设置申请头 */
    if (method === "POST") {if (type == "json") {
          // 参数是 json 类型
         axios.defaults.headers.post["Content-Type"] =
         "application/json;charset=UTF-8";
      } else {
        // 参数是字符串类型
        axios.defaults.headers.post["Content-Type"] =
          "application/x-www-form-urlencoded";
        // params = Qs.stringify(params);
      }
    }
    
    /* 发送申请 */
    return new Promise((resolve,reject) => {
        axios({
            url,
            method,
            type,
            data:method != "GET" ? params : null,
            params:method == "GET" ? params : null
        })
            .then(result => {
                /* 此处能够全局解决接口非凡状态码,比方 token 生效等 */
                resolve(result.data)
            })
            .catch(error => {reject(error)
            })
    })
}

/* await to js */
export const to = promise => {return promise.then(res => [null,res]).catch(error => [error])
}

创立 api.js 文件,设置接口申请解决

import {http, to} from "./http";

//  ---- 全局接口 -----
export const ceshiList = params => {return to(http("json/ceshi.json", params, "GET"));
};

api 应用

import {ceshiList} from "@/http/api.js";
methods:{async getList(){let [err, res] = await ceshiList();
        if (!err) {if (res.result.code == 200) {
            /* 接口申请正确处理 */
            console.log(res);
          }
        }
    }
}

转化 blob 返回的数据

const render = new FileReader();
render.onload = function(){let jsonData = JSON.parse(render.result)
}
render.readAsText(data)
正文完
 0