接口调用-axios

接口调用-axios

axios(官网:https://github.com/axios/axios)是一个基于Promise的Http客户端。

  • 支持浏览器和node.js
  • 支持promise
  • 能拦截请求和响应
  • 自动转换JSON数据

axios基本用法

//1. 引入axios.js
<script type='text/javascript' src="js/axios.js"></script>
//.....
//2.使用
axios.get('http://localhost:8080/data')
	 .then(ret=>{
    //data属性名称是固定的,用于获取后台响应的数据
    console.log(ret.data)
})

axios的常用API

  • get: 查询数据
  • post: 添加数据
  • put: 修改数据
  • delete: 删除数据
//----------get----------
//?传参
axios.get('http://localhost:8080/data?id=101')
	 .then(ret=>{
    console.log(ret.data)
})
//restful风格
axios.get('http://localhost:8080/data/101)
	 .then(ret=>{
    console.log(ret.data)
})
//通过axios提供的params属性传参
axios.get('http://localhost:8080/data'{
      params:{id:101}    
}).then(ret=>{
    console.log(ret.data)
})
//----------post----------
//提交json
axios.post('http://localhost:8080/login',{
      uname: 'admin',
      pwd: '123456'
}).then(ret=>{
    console.log(ret.data)
})
//提交表单
var params = new URLSearchParams();
params.append('uname','admin');
params.append('pwd','123456');
axios.post('http://localhost:8080/login'params).then(ret=>{
    console.log(ret.data)
})
//----------put与post类似----------
//----------delete与get类似----------

axios的响应结果

响应结果的主要属性

  • data: 实际响应回来的数据
  • headers: 响应头信息
  • status: 响应状态码
  • statusText: 响应状态信息

axios全局配置

axios拦截器

  1. 请求拦截器

    在请求之前设置一些信息

    //添加一个请求拦截器
    axios.interceptors.request.use(function(config){
        //在请求之前进行一些信息配置
        config.headers.mytoken='xxxxxxx';
        //config一定要return出去
        return config
    },function(err){
        //处理响应的错误信息
        console.log(err);
    });
    
  2. 响应拦截器

    对响应数据进行前置处理

    axios.interceptors.response.use(function(res){
    	//处理数据
        return res
    },function(err){
        //处理响应的错误信息
        console.log(err);
    });
    
posted @ 2020-11-29 11:48  Maple_XL  阅读(200)  评论(0编辑  收藏  举报