vue知识点: axios

axios

基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用

功能特性

  • 在浏览器中发送 XMLHttpRequests 请求
  • 在 node.js 中发送 http请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 自动转换 JSON 数据
  • 客户端支持保护安全免受 XSRF 攻击

浏览器支持

Browser Matrix

请求方法别名

为方便起见,我们为所有支持的请求方法都提供了别名

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])

axios.options(url[,config])

axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
注意

当使用别名方法时, url、 method 和 data 属性不需要在 config 参数里面指定。

实例

methods:{
  sendGet: function () {
    var _this = this;
    //
    axios.get("/login",{
      params:{
        userId:"123"
      },
      headers:{
        access_token:"abcded"
      }
    }).then(function (res) {
     console.log("res:"+res.data.msg);
     _this.response = res.data;
    }).catch(function (err) {
      console.log("error:"+err);
    });
},
sendPost: function () {
  var _this = this;
  var params = {
    username:"sunnyboysoft@163.com",
            password:"hdeeciu4ZauaDaWF/g+92R8FqNMVA8zoX0UWHinjRM6ND8PMFP9Bt2dr0vGUzZPKXDkzhOJbn3Le0ZcbCiQ1Nx7AIvsrwMzjcSStWNzdyBftzsJS0xsUrtmhqzqaWquXKQoEYgDrP+mNrv0C2ITSpbs+QOql4fPvNSWeAVu54XE=",
               remember:"1",
    pwencode:"1",
    browser_key:"c1eafecb03c5ef07651fb7bd9a7f4b72",
    referer:"http://www.imooc.com"
  }
  //http://www.imooc.com/passport/user/login
  axios.post("/login",params).then(function (res) {
    console.log("res:"+res.data.msg);
    _this.response = res.data;
  }).catch(function (err) {
    console.log("error:"+err);
  });
},
sendJsonp: function () {
  var _this = this;
  jsonp("http://www.imooc.com/course/ajaxskillcourse?cid=796",{
    params:{
      userId:"1001"
    }
  },function (res) {
    console.log("res:"+res.data.msg);
    _this.response = res.data;
  });
},
send: function () {
  var _this = this;
  axios({
    method: 'post',//如果想用get 则 下面的数据用  params:{}来传递
    url: '/user/12345',
    data: {
      firstName: 'Fred',
      lastName: 'Flintstone'
    }
  }).then(function (res) {
    console.log("res:"+res.data.msg);
    _this.response = res.data;
  }).catch(function (err) {
    console.log("error:"+err);
  });;
 }
}

 

 

全局拦截

mounted: function () {
  axios.interceptors.request.use(function (config) {
    console.log("request init.");

    return config;
  })
  axios.interceptors.response.use(function (response) {
    console.log("response init.");
    return response;
  })
},

 

默认配置

你可以为每一个请求指定默认配置。

全局 axios 默认配置

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

自定义实例默认配置

// Set config defaults when creating the instance
var instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置的优先顺序

Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then defaults property of the instance, and finally config argument for the request. The latter will take precedence over the former. Here's an example.

// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
var instance = axios.create();

// Override timeout default for the library
// Now all requests will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;

// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
  timeout: 5000
}); 
posted @ 2018-05-27 12:32  二月花开  阅读(373)  评论(0编辑  收藏  举报