调用axios接口待更新

276 阅读1分钟

aixos三方插件

> 前端数据请求 :promise+ajax +面向对象的封装
> axios 官网 (中文官网)----npm 官网---github 找源代码
http://www.axios-js.com/zh-cn/docs/     #官网地址
 从浏览器中创建 [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)
从 node.js 创建 [http](http://nodejs.org/api/http.html) 请求
支持 [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API
拦截请求和响应
转换请求数据和响应数据
取消请求
自动转换 JSON 数据
客户端支持防御 [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
//基本语法
axios.get('地址+?key=val&key1=val1').then(res=>{})
axios.get('地址',{params:{key:val,key:val1}}).then(res=>{})
axios.post('地址',{key:val,key1:val1}).then(res=>{})

1.用axios来调用接口

//axios.get('地址+?key=val&key1=val1').then(res=>{})
//axios.get('地址',{params:{key:val,key:val1}}).then(res=>{})一般用这个
//用get方式得这样调用
       axios.get('/home/getBannerList',{params:{id:id}})
      .then(res=>{
        console.log(res);
      })
      
 //axios.post('地址',{key:val,key1:val1}).then(res=>{})
      //post这样
       axios.post('/user/register',data)
       .then(res=>{
           log(res)
       })

2.请求图片换头像的方法

//首先html上面得创建一个input上面右一个专门传文件的属性叫做file
 <input type="file" id="igg">
 
 
 uploadFile:function (url, fdKey, fdValue, success){
    const xhr = new XMLHttpRequest();
    const fd = new FormData();
    fd.append(fdKey, fdValue);
  
    xhr.open('POST', SERVER+url);
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        const resData = JSON.parse(xhr.responseText)
        success(resData)
      }
    }
    xhr.send(fd);
  }
 
 // 获取图片
let igg = document.querySelector('#igg')
igg.addEventListener('change' , function(){
    let file = this.files[0];
    http.uploadFile('/book/upload','imgurl',file,function(res){
        console.log(res);
        c =fwz+res.imgurl
    })
})