自学内容网 自学内容网

axios二次封装

一:axios的使用

1.下载

npm i axios -S

2.引入

import axios from 'axios'

3.使用
axios.get()
axios.post()
axios({
url:‘’,
method:‘’,
data:‘post传值方式’
}).then(res=>
console.log(res)//后端给前端返回的数据
)

二:vue中的二次封装

1.终端下载

npm i axios -S

2.main.js中引入

import axios from "axios";

3.封装axios实例–http.js

引入相关内容并创建axios实例

// axios的二次封装
// 引入axios
import axios from 'axios'
// 引入token
import {useUserStore} from '@/stores/userStore'
// 引入路由
// import { useRouter } from 'vue-router';
import router from '@/router';
// 创建axios实例
const httpInstance = axios.create({
    // 设置基地址
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    //  设置超时时间
    timeout: 20000
})

4.添加请求拦截器

config参数
config 对象是由 Axios 库在内部创建并传递给拦截器函数的。当你使用 Axios 发起一个 HTTP 请求时,Axios 会根据你提供的请求配置选项(如 URL、方法、头信息等)创建一个 config 对象。这个对象包含了请求的所有必要信息。
添加响应拦截器并导出

// 拦截器
// 添加请求拦截器
httpInstance.interceptors.request.use(function (config) {
  const useStore=useUserStore()
    // 1.从pinia获取token数据
  const token=useStore.userInfo.token
    // 在发送请求之前做些什么
    //判断token是否存在
    if(token){
    //将token按照后端的要求拼接一下,并且加到请求头上面。
   config.headers.Authorization=`Bearer ${token}`
    }
    //将修改后的config返回出去
   return config;
  }, 
  //没有获取到token,返回错误
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

5.添加响应1拦截器

httpInstance.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 拿到reponse之后可以对响应数据做一些操作
    return response;
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    // 利用拦截器做了一个统一的配置,为什么要写在拦截器里面,因为有很多共同的操作会报错
    ElMessage({
      message:error.response.data.msg,
      type: 'warning',
    })
    // 401token失效处理
    const userStore=useUserStore()
    // 2.跳转到登录页
    if(error.response.status===401){
    // 1.清除本地用户数据
      userStore.clearUserInfo()
    // 2.跳转到登录页
      router.push('/login')
    }
    // 返回错误提示
    return Promise.reject(error);
  }); 
// 导出
export default httpInstance

6.封装请求API

// 获取详情接口,实例里面有请求拦截器,响应拦截器,超时时间,请求基地址。
import httpInstance from "@/utils/http";
export const getCheckoutInfoAPI = () => {
    return httpInstance({
      url:'/member/order/pre'
    })
  }
export const createOrderAPI=(data)=>{
return httpInstance({
  url:'/member/order',
  method:'POST',
  data
})
}

7.组件内使用

//引入相关发送请求的API
import {getCategoryFilterAPI,getSubCategoryAPI} from '@/apis/category.js'
import { onMounted} from 'vue'
// 获取面包屑导航数据
//创建容器
const categoryData=ref([])
const getCategoryData=async ()=>{
//调用API并传入参数
 const res=await getCategoryFilterAPI(route.params.id)
 categoryData.value=res.data.result
}
onMounted(()=>{
  getCategoryData() 
})

原文地址:https://blog.csdn.net/jkjkikik/article/details/142340329

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!