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 })
  • 相关阅读:
    一步一步学习IdentityServer4 (4) 处理特殊需求之-登录等待页面
    php 打包下载
    nginx https反向代理tomcat
    the "ssl" parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf
    layui配置
    vue 学习一
    MyCAT+MySQL 搭建高可用企业级数据库集群——第3章 MyCat核心配置讲解
    第一模块·开发基础-第3章 作业讲解
    《扭转人生的40个哲学提问》 徐帆 著
    零基础学 JavaScript 全彩版 明日科技 编著
  • 原文地址:https://www.cnblogs.com/mengtong/p/11337886.html
Copyright © 2011-2022 走看看