关于axios的完整使用

559 阅读5分钟

关于axios

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

官网的回答

安装

使用 npm:

$ npm install axios 

使用 bower:

$ bower install axios 

使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>  

axios的请求方式

主要请求方式无非就是增删改查,get(请求数据),post(提交数据),delete(删除数据),put(修改数据),patch(更新局部资源),all(并发请求)

get

get请求,就是参数拼接在url后边进行请求,会暴露所有的参数

请求方法:

正常请求直接调用

axios.get('http://localhost:8080').then(res=>{
    console.log(res)
})

axios()

axios({ 
    url:'http://localhost:8080',
    method:'get',
}).then(res=>{
    console.log(res) 
})

携带参数

// 正常请求直接调用
axios.get('http://localhost:8080',{
    params:{
         stationId:10,
         beginDate:2021-12-08 00:00:00
     }
}).then(res=>{
    console.log(res)
})
//axios()
axios({
     url:'http://localhost:8080',
     method:'get',
     params:{
         stationId:10,
         beginDate:2021-12-08 00:00:00
     }
}).then(res=>{
    console.log(res) 
})

post

post请求,就是参数放在body中进行请求参数不会直接暴露,pos一般进行表单的提交或者图片的上传,一般在表单提交的时候,会修改请求头的Content-type改为以application / x-www-form-urlencoded格式发送数据,在上传图片的时候会以multipart/form-data的格式进行发送。

请求方法:

正常请求直接调用

axios.post('http://localhost:8080').then(res=>{
    console.log(res)
})

axios()

axios({ 
    url:'http://localhost:8080',
    method:'post',
}).then(res=>{
    console.log(res) 
})

携带参数

// 正常请求直接调用
axios.post('http://localhost:8080',
    data:{
         stationId:10,
         beginDate:2021-12-08 00:00:00
     }
  ).then(res=>{
    console.log(res)
})
//axios()
const data = {
    stationId:10,
    beginDate:2021-12-08 00:00:00
}
axios({
     url:'http://localhost:8080',
     method:'post',
     data
}).then(res=>{
    console.log(res) 
})

上传表单

// 请求头中修改content-type,并且将参数使用qs进行编码
const data = {
    stationId:10,
    beginDate:2021-12-08 00:00:00
}
axios({
     url:'http://localhost:8080',
     method:'post',
     headers: { 'Content-type': 'application/x-www-form-urlencoded' },
     data: qs.stringify(data),
}).then(res=>{
    console.log(res) 
})

上传图片

// 上传图片需要传参为form对象
let formData = new FormData() // 创建一个form对象
formData.append('fileName',12)
axios({
     url:'http://localhost:8080',
     method:'post',
     headers: { 'Content-type': 'application/x-www-form-urlencoded' },
     formData,
}).then(res=>{
    console.log(res) 
})

put

put方法跟post方法大体相同,

patch

patch方法用来更新局部资源,假设我当前需要更新一个用户的数据,而只更新用户名username,其它的不需要更新,这个时候我们就要使用patch只穿一个用户名username,表示这个请求是一个局部更新,而后端仅更新接收到的字段,put请求也是更新但是如果只传了一个参数的话,就会将剩下的参数置为null

delete

// 正常请求直接调用
axios.delete('http://localhost:8080',
    params:{
         stationId:10
     }
  ).then(res=>{
    console.log(res)
})
//axios()
const data = {
    stationId:10
}
axios({
     url:'http://localhost:8080',
     method:'delete',
     data
}).then(res=>{
    console.log(res) 
})

all

使用all请求,一般是当需要一次性发起多个请求的时候,比如当前需要请求一个用户类型的选择一个用户个人信息的请求,这个时候可以使用all进行并发请求

function getUserInfo(){
    return axios.get('http://localhost:8080/user')
}
function getUserSelect(){
    return axios.get('http://localhost:8080/select/123')
}
axios.all([getUserInfo(),getUserSelect()]).then(axios.spread((acct, perms)=>{
    // 两个请求都完成后
       console.log(acct, perms)
})

其实axios.all()方法就是Pormise.all()方法,在Promise.allthen方法里面是个函数,函数的参数是所有请求的响应组成的数组;而axios.allthen方法里面调用了axios.spread方法,axios.spread方法接收一个函数作为参数,该参数函数的参数也是所有请求的响应

axios的实例

为什么要使用axios的实例,1,当我们在一个项目里边有多个来自后端的不同域名的请求地址,这个时候使用实例进行创建不同的地址,便于我们在项目中的使用,以及维护,2,当我们需要进行对请求的封装的时候需要使用到实例的创建

创建实例的方法

axios.create([config])
const instance = axios.create({   
   baseURL: 'http://localhost:8080/',    // 请求地址
   timeout: 1000,   // 请求超时时间,
   method:'get,post,put,patch,delete',//请求方法
   headers: {'Content-type': 'application/x-www-form-urlencoded'}  // 请求头,
   params:{},//将请求参数拼接在url上,是一个对象       
   data:{}//将请求参数放在请求体里,是一个对象
});

全局配置

axios.defaults.timeout = 10000 // 全局配置

自定义实例默认值

 const instance = axios.create({   baseURL: 'http://localhost:8080/' });

axios的封装

请求拦截器

instance.interceptors.request.use(
  config => {
    // 在请求的时候进行一些处理
    return config;
  },
  error => {
    // 出现错误的话进行什么处理
    return Promise.reject(error);
  }
);

取消拦截器

// 拦截器实例
const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 
// 进行取消
axios.interceptors.request.eject(myInterceptor);

例子:

service3.interceptors.request.use(
  config => {
    const configCopy = config;
    // 判断登录以后的token是否存在
    if (store.getters.token) {
    // 存在就在请求头上添加token
      configCopy.headers['Lt-Authorization'] = `carrier.${getToken()}`;
    }
    return configCopy;
  },
  error => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

这里其实还可以做一些别的处理,这只是一个例子,还可以在里边进行一些比如loading的加载,请求的时候加载,失败的时候或者成功的时候去掉

请求响应器

service.interceptors.response.use(
  response => {
    // 做请求响应成功的处理
    return response;
  },
  error => {
    console.log(`err${error}`); // for debug
    // 请求失败的响应
    return Promise.reject(error);
  }
);

响应跟拦截其实都是成功的时候进入then中,失败的时候进入catch中,在请求拦截跟响应中,他们的error返回的promise都会进入catch中。

例子

service.interceptors.response.use(
  response => {
    const res = response.data;
    // 判断当前的Type是不是blob
    if (response.config.responseType !== 'blob') {
    // 判断返回的code是不是成功
      if (res.code !== 200) {
        console.error(res.message || 'Error')
        return Promise.reject(new Error(res.message || 'Error'));
      }
    }

    return res;
  },
  error => {
    console.log(`err${error}`); //打印错误
     Message({
       message: error.message,
       type: 'error',
       duration: 5 * 1000,
     });
    return Promise.reject(error);
  }
);

在响应里边进行自己的处理,