封装axios,自定义header,请求拦截器

封装axios,自定义header,请求拦截器

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

点击这里前往axios官网,了解安装详情
1、封装axiso
新建js文件并将一下文件复制。

import axios from 'axios'
import Vue from 'vue'

import url from '@/assets/js/url' //你的url文件
import qs from 'qs'//格式化字符串工具

axios.interceptors.request.use( // 正文开始
  (config) => {
    if (config.method === 'post') {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 区分生产模式和开发模式
function setHost() {
  return 'http://' + ''
}
let location = process.env.VUE_APP_LOACTION || setHost()
// axios默认配置
axios.defaults.timeout = 10000 // 超时时间
axios.defaults.baseURL = location // 默认地址
axios.defaults.headers['Content-Type'] =
'application/x-www-form-urlencoded;charset=UTF-8'
let v = new Vue()
/**
 *
 * 接收一个对象
 *  method 请求类型
 *  url 请求链接
 *  data 请求数据
 *  then 回调方法
 */
let axiosHttp = (obj) => {
  let loading = v.$loading({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0)',
  })
  let oData = obj.method == 'GET' ? obj.data : {}
  let params = obj.params || oData
  axios({
    method: obj.method || 'POST',
    url: obj.url || '',
    data: obj.data || '',
    params,
  })
    .then(function(res) {
      loading.close()
      let data = res.data
      if (data.code != 0) {
        v.$message({
          type: 'error',
          message: data.message,
        })
        return
      } else if (data.code == 1) {
        v.$alert(data.message, '系统提示')
        obj.catch && typeof obj.catch == 'function' && obj.catch(res)
      } else if (data.code == 999) {
        // 999重新登陆
        process.env.NODE_ENV == 'production' &&
          v.$alert(data.message, '系统提示', {
            callback: () => (window.location.href = '/adminLogin'),
          })
      } else if (data.code == 444) {
        // 444是404页面
        // v.$router.push({name:'error'});
      } else {
        obj.then && typeof obj.then == 'function' && obj.then(res)
      }
    })
    .catch(function(error) {
      loading.close()
      console.log(error.response)
      if (error.response) {
        console.log(error.response.status)
        if (error.response.status != 200) {
          v.$message({
            type: 'error',
            message: error.response.statusText,
          })
        }
      }
    })
} //正文结束
export { axiosHttp}

2、完成步骤一后
你可以按照一下发起一个ajax请求:

     index(self, name) {
    let config = {
      category_name: self[name].category_name,
      sort: self[name].sort,
      icon: self['url'],
      describe: self[name].describe,
    }
    console.log(config)
    axiosHttp({
      url: url.insertCategory,
      data: config,
      then(res) {
        console.log(res.data.data)
        if (res.data.code == 0) {
          self.$message({
            type: 'success',
            message: res.data.message,
          })
          self.dialogVisible = false
          self.$api.getCategoryList(self, 'schoolData')
        }
      },
    })
  },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是使用TypeScript封装Axios拦截器的示例代码: ```typescript import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; class AxiosInterceptor { private axiosInstance: AxiosInstance; constructor(baseURL: string, timeout = 10000) { this.axiosInstance = axios.create({ baseURL, timeout, }); this.requestInterceptor(); this.responseInterceptor(); } private requestInterceptor(): void { this.axiosInstance.interceptors.request.use( (config: AxiosRequestConfig) => { // 在发送请求之前做些什么 // 比如添加token到header中 const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, (error) => { // 对请求错误做些什么 return Promise.reject(error); } ); } private responseInterceptor(): void { this.axiosInstance.interceptors.response.use( (response: AxiosResponse) => { // 对响应数据做点什么 return response; }, (error) => { // 对响应错误做点什么 if (error.response.status === 401) { // token失效,跳转到登录页 window.location.href = '/login'; } return Promise.reject(error); } ); } public get<T>(url: string, config?: AxiosRequestConfig): Promise<T> { return this.axiosInstance.get<T>(url, config); } public post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> { return this.axiosInstance.post<T>(url, data, config); } public put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> { return this.axiosInstance.put<T>(url, data, config); } public delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> { return this.axiosInstance.delete<T>(url, config); } } export default AxiosInterceptor; ``` 这个类使用了Axios拦截器功能,在请求发送前和响应返回后进行一些操作,比如添加token到请求header中,或者在token失效后跳转到登录页。类中还封装了常用的get、post、put、delete等HTTP请求方法,可以直接调用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

铁锅炖大鹅(e)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值