vue封装request携带token

2022-03-18 09:15:02

vue封装request携带token

封装带token的和不带token的

import axiosfrom'axios';import jwtfrom'../utils/auth/jwt';import loginfrom'../request/login';import jsconfigfrom'../request/jsonConfig';import clientfrom'../utils/myconfig/client';classreq{/**
     * 请求头部携带token
     */initHeader(header){if(!header) header={};if(!header.Authorization) header.Authorization= jwt.getToken();
        header['Content-Type']='application/json';
        header['Client-Type']= jsconfig.clientType.H5;//客户端类型
        header['App-Version']= jsconfig.version//客户端版本let cliInfo= client.getClientInfo();

        header['Client-Id']= cliInfo? cliInfo.clientId:'';//客户端IDreturn header;}send(param){
        param.headers=this.initHeader(param.header);if(!param.data) param.data={};axios(param).then(res=>{if('function'==typeof param.success){
                param.success(res.data);}}).catch(err=>{if('function'==typeof param.fail){
                param.fail(err);}});}/**
     * 普通请求(不带token)
     * @param {object} param 请求的参数
     */get(param){
        param.method='GET';if(param.data){
            param.params= param.data;}this.send(param);}post(param){
        param.method='POST';this.send(param);}/**
     * 需要携带token的请求
     * @param {string} method 请求方式GET/POST等
     * @param {object} param 请求的参数
     */reTokenQuest(method, param){//当前token是否可用let token= jwt.getToken();if(!token){//当前token不可用则启用TempSecret登录
            param.method= method;
            login.doTempSecretLogin(param);return;}

        method= method.toUpperCase();if(method=='GET'){this.get(param);}elseif(method=='POST'){this.post(param);}}}const request=newreq();exportdefault request

封装结束,引入就可以使用了。

  • 作者:Auaaa
  • 原文链接:https://blog.csdn.net/Auaaa/article/details/121773226
    更新时间:2022-03-18 09:15:02