Vue之封装二次axios

简介: Vue之封装二次axios

第一步,首先安装axios,这里推荐局部安装


npm i -D axios


第二步,在src目录下创建request文件夹,然后在里面创建两个文件http.js、api.js


http.js


import axios from 'axios'
// 环境的切换
if (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = '' // 开发环境
} else if (process.env.NODE_ENV === 'debug') {
  axios.defaults.baseURL = '' // 调试环境
} else if (process.env.NODE_ENV === 'production') {
  axios.defaults.baseURL = '' // 生产环境
}
axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8;multipart/form-data'
// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
    // 即使本地存在token,也有可能token是过期的,所以在响应拦截器中要对返回状态进行判断
    // const token = this.$store.state.Authorization
    // token && (config.headers.Authorization = token)
    // return config
  if (localStorage.getItem('Authorization')) {
        config.headers.Authorization = localStorage.getItem('Authorization');
      }
  return config;
  },
  error => {
    return Promise.error(error)
  })
// 响应拦截器
axios.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return Promise.resolve(response)
    } else {
      return Promise.reject(response)
    }
  },
  // 服务器状态码不是200的情况
  error => {
    if (error.response.status) {
      switch (error.response.status) {
        // 401: 未登录
        // 未登录则跳转登录页面,并携带当前页面的路径
        // 在登录成功后返回当前页面,这一步需要在登录页操作。
        case 401:
          this.$router.replace({
            path: '/Login',
            query: { redirect: this.$router.currentRoute.fullPath }
          }) 
          break;
        // 403 token过期
        // 登录过期对用户进行提示
        // 清除本地token和清空vuex中token对象
        // 跳转登录页面
        case 403:
          this.$toast({
            message: '登录过期,请重新登录',
            duration: 1000,
            forbidClick: true
          })
          // 清除token
          localStorage.removeItem('Authorization')
          this.$store.commit('changeLogin', null)
          // 跳转登录页面,并将要浏览的页面fullPath传过去,登录成功后跳转需要访问的页面
          setTimeout(() => {
            this.$router.replace({
              path: '/Login',
              query: {
                redirect: this.$router.currentRoute.fullPath
              }
            })
          }, 1000)
          break;
        // 404请求不存在
        case 404:
          this.$toast({
            message: '网络请求不存在',
            duration: 1500,
            forbidClick: true
          })
          break;
        // 其他错误,直接抛出错误提示
        default:
          this.$toast({
            message: error.response.data.message,
            duration: 1500,
            forbidClick: true
          })
      }
      return Promise.reject(error.response)
    }
  }
)
/**
 * get方法,对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get (url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}
/**
 * post方法,对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post (url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err.data)
      })
  })
}


api.js


import { get, post } from './http'
export const api1 = p1 => get('https://xxx/v5/weather?city=qingdao&key=1b47b16e4aa545eaa55a66f859ac0089', p1)
export const api2 = p2 => get('https://xxx/v5/weather?city=taian&key=1b47b16e4aa545eaa55a66f859ac0089', p2)
export const api3 = p => post('https://xxx/svserver/upload/', p)


第三步,应用到组件


<template>
  <div class="hello">
    <button @click="api1">青岛</button>
    <button @click="api2">泰安</button>
    <input type="file" accept="video/*" name="video" @change="api3()" id="file1">
  </div>
</template>
<script>import { api1, api2, api3 } from '@/request/api'// 导入我们的api接口
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
  // get方法
    api1 () {
      // 调用api接口,并且提供了两个参数
      api1({
        type: 0,
        sort: 1
      }).then(res => {
        // success
        console.log(res)
      }).catch((error) => {
        // error
        console.log(error)
      })
    },
    api2 () {
      api2({
        type: 0,
        sort: 1
      }).then(res => {
        // success
        console.log(res)
      }).catch((error) => {
        // error
        console.log(error)
      })
    },
    // post方法
      let postData = {
          lookid: id,
          look: num
        }
        api3(postData).then(res => {
          // success
          console.log(res)
        }).catch((error) => {
          // error
          console.log(error)
        })
      //原始的post方法
      // this.$axios({
      //   url: 'https://xxx/svserver/upload/',
      //   method: 'POST',
      //   headers: {
      //     'Content-Type': 'multipart/form-data'
      //   },
      //   data: data
      // }).then((response) => {
      //   // success
      // })
      //   .catch((error) => {
      //     // error
      //     console.log(error)
      //   })
    }
  }
}
</script>



相关文章
|
1月前
|
资源调度 JavaScript API
vue3封装城市联动组件
vue3封装城市联动组件
|
10天前
封装axios的get、post方法
本文介绍了如何封装axios的get和post方法,并展示了具体的代码实现,包括使用axios创建实例、设置请求拦截器以及定义get和post函数。
25 2
|
2月前
|
JavaScript 前端开发
【Vue面试题二十五】、你了解axios的原理吗?有看过它的源码吗?
这篇文章主要讨论了axios的使用、原理以及源码分析。 文章中首先回顾了axios的基本用法,包括发送请求、请求拦截器和响应拦截器的使用,以及如何取消请求。接着,作者实现了一个简易版的axios,包括构造函数、请求方法、拦截器的实现等。最后,文章对axios的源码进行了分析,包括目录结构、核心文件axios.js的内容,以及axios实例化过程中的配置合并、拦截器的使用等。
【Vue面试题二十五】、你了解axios的原理吗?有看过它的源码吗?
|
2月前
|
JavaScript 前端开发
【Vue面试题二十七】、你了解axios的原理吗?有看过它的源码吗?
文章讨论了Vue项目目录结构的设计原则和实践,强调了项目结构清晰的重要性,提出了包括语义一致性、单一入口/出口、就近原则、公共文件的绝对路径引用等原则,并展示了单页面和多页面Vue项目的目录结构示例。
|
26天前
|
JavaScript 前端开发 开发者
vue中使用axios请求post接口,请求会发送两次
vue中使用axios请求post接口,请求会发送两次
|
11天前
|
JavaScript
Vue2.0、Vue3.0分别使用v-model封装组件[Vue必会]
本文介绍了在Vue 2和Vue 3中如何使用`v-model`来实现组件间的双向数据绑定,包括在Vue 2中使用`value`和`input`事件,以及在Vue 3中使用`modelValue`和`update:modelValue`事件的方法。
55 22
|
8天前
|
JavaScript
vue 中 axios 的安装及使用
本文介绍了在Vue项目中安装和使用axios的方法。首先通过命令`npm install axios --save-dev`安装axios,然后在组件的`created`生命周期钩子中使用`axios.get`异步获取数据,并将获取的数据更新到组件的`data`中。文中提供了完整的示例代码,包括安装命令、验证安装成功的步骤、Vue组件的模板、脚本和样式。
vue 中 axios 的安装及使用
|
13天前
|
JSON 资源调度 JavaScript
Vue框架中Ajax请求的实现方式:使用axios库或fetch API
选择 `axios`还是 `fetch`取决于项目需求和个人偏好。`axios`提供了更丰富的API和更灵活的错误处理方式,适用于需要复杂请求配置的场景。而 `fetch`作为现代浏览器的原生API,使用起来更为简洁,但在旧浏览器兼容性和某些高级特性上可能略显不足。无论选择哪种方式,它们都能有效地在Vue应用中实现Ajax请求的功能。
18 4
|
11天前
|
JavaScript 前端开发
vue配合axios连接express搭建的node服务器接口_简单案例
文章介绍了如何使用Express框架搭建一个简单的Node服务器,并使用Vue结合Axios进行前端开发和接口调用,同时讨论了开发过程中遇到的跨域问题及其解决方案。
12 0
vue配合axios连接express搭建的node服务器接口_简单案例
|
JavaScript 前端开发