Fork me on github

封装axios

 axios({
                            method: 'get',
                            url: '/SystemManage/SetMeal/sensorlisttype?userid=' + userId//,
                        })
                        .then(function (response) {
                        })
                        .catch(function (error) { // 请求失败处理
                            console.log(error);
                        })
 axios.get('/Video/GetServiceCallRecords', {
                        params: {
                           serviceCallNum: '',//客服帐号
                           appMemberName: number,//手机号
                           biginTime: '',//开始时间
                       }
                   })
                       .then(function (response) {
                       })
                       .catch(function (error) {
                           console.log(error);
                       });

axios post请求

  axios.post('/Video/getTrtcToken', {
                      acount: 'admin_nikoyose_3033654362',
                      paswd: 'admin_nikoyose_3033654362',
                      appid: '1400552732',
                        })
                       .then(function (response) {
                           This.token = response.data.token
                      })
                    .catch(function (error) {
                        console.log(error);
                    });

axios请求携带token

(86条消息) vue之 axios的post请求及headers token方式_axios post header_JessicaLilyAn的博客-CSDN博客

 

vue封装axios

 

 

loading.js(请求接口时,加载中)

import { Loading } from 'element-ui'

let loadingCount = 0
let loading

const startLoading = () => {
  loading = Loading.service({
    lock: false,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

const endLoading = () => {
  loading.close()
}

export const showLoading = () => {
  if (loadingCount === 0) {
    startLoading()
  }
  loadingCount += 1
}

export const hideLoading = () => {
  if (loadingCount <= 0) {
    return
  }
  loadingCount -= 1
  if (loadingCount === 0) {
    endLoading()
  }
}

request.js

import axios from 'axios' // 安装axios后引入
//import qs from 'qs'
import * as loading from './loading' // elementui的loading

const baseUrl = "http://192.168.253.217:6003";
const instance = axios.create({
    baseURL: baseUrl,
    timeout: 6000
})
function request(config) {
    return instance(config)
}
function GetUser(data) {
    return request({
        url: data.url,
        method: data.method,
        data: data.data,
        'auth': data.token
    })
}
//解析token
// export const decodeJWT = function (token: string): TokenData {
//     if (!token) {
//       return null;
//     }
//     const decoded = jwt.decode(token, { complete: true });
//     return decoded?.payload;
//   };
// axios实例创建好之后,开始使用request拦截器对axios请求配置做统一处理
//request拦截器==>对请求参数做处理
instance.interceptors.request.use(config => {
    //console.log('正在请求数据')
    if (!config.url.includes('/api/auth/selfhealth')) {
        loading.showLoading()
    }

    config.method === 'post' ?
        // config.data = qs.stringify({
        //     ...config.data
        // }) :
        config.data = {
            ...config.data
        } :
        config.params = {
            ...config.params
        }
    if (config.url != '/api/auth/login') {
        let currentTime = new Date().getTime()
        //token过期时间
        let expirationTime = new Date(JSON.parse(localStorage.expiration)).getTime()

        if (currentTime < expirationTime) {
            //token未过期
            config.headers.Authorization = 'Bearer ' + JSON.parse(localStorage.token); //将token设置成请求头
        } else {
            //token已过期
            alert("登录已超时,请重新登录");
        }
    }
    return config
}, error => { // 请求错误处理
    // app.$vux.toast.show({
    //     type: 'warn',
    //     text: error
    // });
    console.log('请求错误处理')
    Promise.reject(error)
})//respone拦截器==>对响应做处理
instance.interceptors.response.use(
    response => { // 成功请求到数据
        loading.hideLoading()
        //console.log('成功请求到数据', response)
        // 这里根据后端提供的数据进行对应的处理
        // if (response.data.code === 0) {
        //     console.log('instance', response.data)
        //     return response.data
        // } else {
        //     console.log('warn')
        //    // return response.data
        // }
        return response.data
    },
    error => { // 响应错误处理
        loading.hideLoading()
        console.log('error', error)
        // let text = JSON.parse(JSON.stringify(error)).response.status === 404 ?
        //     '404' :
        //     '网络异常,请重试'
        // app.$vux.toast.show({
        //     type: 'warn',
        //     text: text
        // });
        //console.log('warn', text)
        return Promise.reject(error)
    }
)
export {
    GetUser,
    //GetUser2,
    instance,
}

 

index.js

import axios from 'axios';
import qs from 'qs';
import {instance,instance2} from './request'

export const GetWeekReport = (data1) => {
  let data = JSON.parse(data1)
  return instance({
    url: "/api/v2/report/week?rsid=" + data.userid + "&date=" + data.date,
    method: 'get',
  })
}

.vue调用接口

  import { GetWeekReport } from "../../api/index";

 GetWeekReport(JSON.stringify(data)).then((data) => {
})

登录接口存储token (拦截器不拦截此接口)

  //存储token
          window.localStorage["token"] = JSON.stringify(res.token);
          //存储token过期时间
          window.localStorage["expiration"] = JSON.stringify(res.expiration);

axios请求 'Content-Type: multipart/form-data' 格式

request.js

instance2.interceptors.request.use(config => {
    console.log('********************************', {
        ...config.data
    },config.method === 'post')
    config.method === 'post' ?
      
        //config.data = 'roomid=16246127010&userid=18503483557':
        config.params = config.data:
        config.params = {
            ...config.params
        }
     
     
    if (config.url != '/api/auth/login?acount=admin_nikoyose_3033654362&paswd=admin_nikoyose_3033654362&appid=1400552732&api-version=1') {
        config.headers.Authorization = 'Bearer ' + JSON.parse(localStorage.trtctoken); //将token设置成请求头
        config.headers['Content-Type'] ='application/x-www-form-urlencoded;charset=UTF-8'
    Date(JSON.parse(localStorage.trtcexpiration)).getTime()
   JSON.parse(localStorage.trtctoken); //将token设置成请求头
    }
    return config
}, error => { // 请求错误处理
 
    console.log('请求错误处理')
    Promise.reject(error)
})

index.js

export const getTrtcLogin = data => {
  return instance2({
    url: '/api/auth/login?acount=admin_nikoyose_3033654362&paswd=admin_nikoyose_3033654362&appid=1400552732&api-version=1',
    method: 'post',
    data: data
  })
}

 .vue

import { getTrtcLogin } from "../../api/index";
 
const params = {
        acount: "admin_nikoyose_3033654362",
        paswd: "admin_nikoyose_3033654362",
        appid: 1400552732,
      };
getTrtcLogin(params).then((res) => {
})

 axios请求接口携带token

 this.axios.interceptors.request.use(config=>{
        const token=localStorage.getItem('token')
        // if(token){
            token?config.headers.Authorization=token:null;
        // }
        return config
      });
      this.axios.interceptors.response.use(res=>{
          if(res.data.res_code=== 401){
              // router.replace('/login');
              localStorage.removeItem('token')
          }
          return res
      })

 

vue中华使用axios

main.js

import axios from 'axios'
Vue.prototype.axios = axios

 

.vue中使用

this.axios({
          method: 'POST',
          url: '/api/v1/Operators/login?operatorId=admin&password=nikoyose.nko851896333',
        })
      .then(response => {
          localStorage.setItem('token',"Bearer "+ response.data.token)
      }, error => {
          console.log('错误', error.message)
      })

 

axios提交post请求

 axios.post('/OnlineTest/PostFallUpLoad', {
                            queryJson: JSON.stringify(queryJson)
                        })
                            .then(response => {
                                if (response.data.code === 0) {
                                    console.log('存储数据成功')
                                } else {
                                    console.log('存储数据失败')
                                }
                            })//提交录入的问题
                            .catch(function (error) {
                                this.$message.error('调用接口失败');
                            })
 this.axios({
          method: 'POST',
          url: '/api/v1/Operators/login?operatorId=admin&password=nikoyose.nko851896333',
        })
      .then(response => {
          localStorage.setItem('token',"Bearer "+ response.data.token)
      }, error => {
          console.log('错误', error.message)
      })

 

 

 

 

 

 

 

 

 
posted @ 2022-03-23 11:33  我の前端日记  阅读(15)  评论(0编辑  收藏  举报
Copyright © 2021 LinCangHai
Powered by .NET 5.0 on Kubernetes