axios

<!--1. axios发请求 -->
- 支持promise  - 能拦截请求和响应  - 自动转换JSON数据 - 能转换请求和响应数据
  1.axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,本质上也是对原生XHR的封装,
  只不过它是Promise的实现版本,符合最新的ES规范,尤雨溪推荐大家用axios替换JQuery ajax

  2.需下载引入<script type="text/javascript" src="js/axios.js"></script>

  3.//从浏览器中创建 XMLHttpRequest  //支持 Promise API  //客户端支持防止CSRF
    //提供了一些并发请求的接口  //拦截请求和响应  //转换请求和响应数据
    //取消请求  //自动转换JSON数据

# 1. 发送get 请求 
axios.get('http://localhost:3000/adata').then(function(ret){ 
  #  拿到 ret 是一个对象      所有的对象都存在 ret 的data 属性里面
  // 注意data属性是固定的用法,用于获取后台的实际数据
  // console.log(ret.data)
  console.log(ret)
})

<!-- # 2.  get 请求传递参数 -->
# 2.1  通过传统的url  以 ? 的形式传递参数
axios.get('http://localhost:3000/axios?id=123').then(function(ret){
  console.log(ret.data)
})

# 2.2  restful 形式传递参数            //restful是一种请求规范
axios.get('http://localhost:3000/axios/123').then(function(ret){
  console.log(ret.data)
})
# 2.3  通过params  形式传递参数   //params固定写法,axios会格式处理
axios.get('http://localhost:3000/axios', {
  params: {
    id: 789
  }
}).then(function(ret){
  console.log(ret.data)
})

<!-- #3 axios delete 请求传参     传参的形式和 get 请求一样 -->
axios.delete('http://localhost:3000/axios', {
  params: {
    id: 111
  }
}).then(function(ret){
  console.log(ret.data)
})

<!-- # 4  axios 的 post 请求 -->
# 4.1  通过选项传递参数
axios.post('http://localhost:3000/axios', {
  uname: 'lisi',
  pwd: 123
}).then(function(ret){
  console.log(ret.data)
})

# 4.2  通过 URLSearchParams  传递参数 
var params = new URLSearchParams();
params.append('uname', 'zhangsan');
params.append('pwd', '111');
axios.post('http://localhost:3000/axios', params).then(function(ret){
  console.log(ret.data)
})

 <!-- #5  axios put 请求传参   和 post 请求一样  -->
axios.put('http://localhost:3000/axios/123', {
  uname: 'lisi',
  pwd: 123
}).then(function(ret){
  console.log(ret.data)
})

<!--2. axios 全局配置 -->
#  配置请求的基准URL地址
axios.defaults.baseURL = 'https://api.example.com';
#  配置公共的请求头
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
# 配置公共的 post 的 Content-Type
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

<!-- 3.axios 拦截器 -->
# 1. 请求拦截器   //请求拦截器的作用是在请求发送前进行一些操作
axios.interceptors.request.use(function(config) {
  console.log(config.url)
  # 1.1  任何请求都会经过这一步   在发送请求之前做些什么   
  config.headers.mytoken = 'nihao';
  # 1.2  这里一定要return   否则配置不成功  
  return config;
}, function(err){
   #1.3 对请求错误做点什么    
  console.log(err)
})
#2. 响应拦截器   //响应拦截器的作用是在接收到响应后进行一些操作
axios.interceptors.response.use(function(res) {
  #2.1  在接收响应做些什么  
  var data = res.data;
  return data;
}, function(err){
  #2.2 对响应错误做点什么  
  console.log(err)
})
原文地址:https://www.cnblogs.com/xm0328/p/13783081.html