[Vue]axios的使用

1、axios 简介

1.axios特征html

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它自己具备如下特征:vue

    • 从浏览器中建立 XMLHttpRequest
    • 从 node.js 发出 http 请求
    • 支持 Promise API
    • 拦截请求和响应
    • 转换请求和响应数据
    • 取消请求
    • 自动转换JSON数据
    • 客户端支持防止 CSRF/XSRF

2.引入方式:

//使用npm
$ npm install axios
//使用bower
$ bower install axios
//或者使用cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

 

安装其余插件的时候,能够直接在 main.js 中引入并使用 Vue.use()来注册,可是 axios并非vue插件,因此不能 使用Vue.use(),因此只能在每一个须要发送请求的组件中即时引入。node

为了解决这个问题,咱们在引入 axios 以后,经过修改原型链,来更方便的使用。ios

//main.jsnpm

import axios from 'axios'
Vue.prototype.$http = axios

3.使用 $http命令axios

在 main.js 中添加了这两行代码以后,就能直接在组件的 methods 中使用 $http命令api

methods: {
  postData () {
    this.$http({
      method: 'post',
      url: '/user',
      data: {
        name: 'xiaoming',
        info: '12'
      }
   })
}

2、下面来介绍axios的具体使用:浏览器

 

1.axios(config)

// 发送一个 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

2.axios(url[, config])

// 发送一个 GET 请求 (GET请求是默认请求模式)
axios('/user/12345');

请求方法别名

为了方便起见,已经为全部支持的请求方法提供了别名。当使用别名方法时,不须要在config中指定url,method和data属性。服务器

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]])

2.1执行 GET 请求

// 向具备指定ID的用户发出请求
$http.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
// 也能够经过 params 对象传递参数
$http.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

2.2执行 POST 请求并发

$http.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

3.并发

帮助函数处理并发请求。

    • axios.all(iterable)
    • axios.spread(callback)

执行多个并发请求

function getUserAccount() {
  return $http.get('/user/12345');
}
function getUserPermissions() {
  return $http.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
  .then($http.spread(function (acct, perms) {
    //两个请求现已完成
  }));

4.建立实例

您可使用自定义配置建立axios的新实例。

axios.create([config])

var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

实例方法

可用的实例方法以下所示。 指定的配置将与实例配置合并。

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]])
axios#getUri([config])

config详细见:http://www.javashuo.com/article/p-qoudlanx-ho.html

5.响应格式

请求的相应包含如下信息

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}

使用 then 时,您将收到以下响应:

axios.get('/user/12345')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

6.配置默认值

6.1全局默认值

 

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';

 

6.2自定义实例的默认值

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

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

6.3配置的优先级

config中配置的值>实例方法的defaults的配置值>库中defaults的配置值

// 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
//
const instance = axios.create();

// Override timeout default for the library
// Now all requests using this instance 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
//config的配置值
instance.get('/longRequest', {
  timeout: 5000
});

7.拦截器

你能够截取请求或响应在被 then 或者 catch 处理以前

//添加请求拦截器
axios.interceptors.request.use(function(config){
     //在发送请求以前作某事
     return config;
   },function(error){
     //请求错误时作些事
     return Promise.reject(error);
   });
 
//添加响应拦截器
axios.interceptors.response.use(function(response){
     //对响应数据作些事
      return response;
   },function(error){
     //请求错误时作些事
     return Promise.reject(error);
   });
//去除拦截器
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

8.处理错误

axios.get('/ user / 12345')
   .catchfunction(error){
     if(error.response){
       //请求已发出,但服务器使用状态代码进行响应
       //落在2xx的范围以外
       console.log(error.response.data);
       console.log(error.response.status);
       console.log(error.response.headers);
     } else {
       //在设置触发错误的请求时发生了错误
       console.log('Error',error.message);
     }}
     console.log(error.config);
   });

您可使用validateStatus配置选项定义自定义HTTP状态码错误范围。

axios.get('/ user / 12345',{
   validateStatus:function(status){
     return status < 500; //仅当状态代码大于或等于500时拒绝
   }}
})

9.取消请求

使用cancel token取消请求

9.1使用CancelToken.source工厂建立一个cancel token

 

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

 

9.2经过传递一个执行函数给CancelToken构造函数来建立一个cancel token:

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

 

参照官网:http://www.axios-js.com/docs/

 翻译:http://www.javashuo.com/article/p-uubusycu-hp.html

相关文章
相关标签/搜索