axios 封装使用

axios封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import axios from "axios";
  
  // 使用create创建axios实例
  const Service=axios.create({
  timeout:8000,
  baseURL:"http:xxxxx/",
  headers:{
      "Content-type":"application/json;charset=utf-8",
      "Authorization" : 登陆后拿到的token
  }
  })

  // 请求拦截-增加loading,对请求做统一处理
  Service.interceptors.request.use(config=>{
  loadingObj=ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    return config
  })

  // 响应拦截-对返回值做统一处理
  Service.interceptors.response.use(response=>{
  const data=response.data
  return data
  },error=>{
  })

  // post请求
  export const post=config=>{
  return Service({
  ...config,
  method:"post",
  data:config.data
  })
  }
  
  // get请求
  export const get=config=>{
  return Service({
  ...config,
  method:"get",
  params:config.data
  })
  }
接口封装
import {get,post} from "./service"
export const loginApi=data=>{
return post({
    url:'/login',
    data
})
}
使用
import {loginApi} from "@/util/request"

loginApi(data).then(res=>{})
引用: 在实际工作项目中,使用axios进行请求时,可能需要访问多个服务地址,而这些服务请求和响应的结构也可能都完全不同。为了更好地处理这种情况,我们可以通过axios.create()方法创建不同的实例来进行处理。创建实例的好处是可以单独为不同的实例配置拦截器、超时时间、请求头等。比如,可以为axios1配置某种拦截器,而为axios2配置另一种拦截器,以满足不同的需求。 引用: 创建axios实例时,可以传入一个配置对象来对实例进行配置,如果不传入配置对象,则默认使用全局的配置。如果创建了实例,但又想修改实例的某些配置,可以直接通过实例对象进行修改。需要注意的是,axios请求配置的优先级是axios请求配置 > axios实例配置 > axios全局配置。 针对axios实例的使用,可以使用实例的get、post、post_json等方法来发送请求。这些方法的使用方式与全局的axios.get、axios.post等方法类似,只是需要通过实例对象来调用。具体使用案例可以参考以下代码: ``` // 创建axios实例 const instance = axios.create({ baseURL: 'http://api.example.com', // 设置请求的基础URL timeout: 5000, // 设置超时时间为5秒 headers: { 'Content-Type': 'application/json' // 设置请求头的Content-Type为JSON } }); // 发送GET请求 instance.get('/users') .then(res => { console.log(res.data); }) .catch(error => { console.error(error); }); // 发送POST请求 instance.post('/users', { name: 'John', age: 25 }) .then(res => { console.log(res.data); }) .catch(error => { console.error(error); }); ``` 以上示例展示了如何创建axios实例,并使用实例的get和post方法发送请求。你可以根据自己的需求配置实例,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值