zoukankan      html  css  js  c++  java
  • axios的常用方法

    执行get请求

     axios.get("url?id=13",{
        /*params:{
          name:123 //带参请求
        }*/
        })
        .then(res=>{
           //成功后执行
        }) 
        .cache(err=>{
          //错误执行
        }) 
        .finally(function(){
          //总是执行
         })

    执行post请求

      axios.post("/user",{
         firstName:"Fred",
         lastName:"ssass"
       })
      .then(function (response) {
         console.log(response);
      })
      .catch(function (error) {
         console.log(error);
       })

    执行并发请求

    function getUserAccount(){
        return axios.get("/user/12");
      }
      function getUserPermissions(){
        return axios.get("/user/123/permission")
      }
      axios.all([getUserAccount(),getUserPermissions()])
        .then(axios.spread(function(acct,perms){
          //两个请求都成功
        }))

    通过传递相关配置来进行请求

    //post请求 
     axios({
        method:'post',
        url:'',
        data:{
          firstName:'M',
          lastName:'t'
        }
      })
    //get请求
     axios({
        method:'get',
        url:'',
        responseType:'stream'
      })
        .then(function(response){
            response.data.pipe(fs.createWriteStream('a.jpg'))
        })

    创建实例

    const instance = axios.create({
      baseURL:'',//方便的设置路由的转发规则
      headers:{"X-Custom-header":foobar}//通过请求头设置一些信息
        
    })

    拦截器interceptors

    配置拦截器,对请求与响应进行处

    // 添加请求拦截器
    axios.interceptors.request.use(function (config) {  
      //发送请求之前做一些事情
        return config;
      }, function (error) {
       //捕捉错,对错误进行处理
        return Promise.reject(error);
      });
    
    // 添加响应拦截器
    axios.interceptors.response.use(function (response) {
        //对响应结果做一些处理
      /*
        if(data.code===200){
          return data.data
        }else{
         return response 
        }
      */
        return response;
      }, function (error) {
        return Promise.reject(error);
      });

    params 的用法

    let params = {
        keyWord: null,
        name: 'xxx',
        age: 22
    }
    // 为 null 的属性都会被过滤掉,最终的请求 url 是 /person?name=xxx&age=22
    instance.get('/person', { params })
  • 相关阅读:
    第二次会议
    第五次团队会议
    作业六:团队项目——编写项目的Spec
    DFD数据流程图
    第四次会议
    精通 VC++ 实效编程280例 03 控制栏
    1.窗体与界面设计工具栏设计
    HTML5开发 Local Storage 本地存储
    1.窗体与界面设计菜单应用实例
    精通 VC++ 实效编程280例 02 菜单和光标
  • 原文地址:https://www.cnblogs.com/mengtong/p/11337886.html
Copyright © 2011-2022 走看看