vue2.0之axios使用详解

axios

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

功能特性

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

浏览器支持

Browser Matrix

安装

使用 bower:

$ bower install axios

使用 npm:

$ npm install axios

例子

发送一个 GET 请求

 
  1. // Make a request for a user with a given ID

  2. axios.get('/user?ID=12345')

  3. .then(function (response) {

  4. console.log(response);

  5. })

  6. .catch(function (response) {

  7. console.log(response);

  8. });

  9.  
  10. // Optionally the request above could also be done as

  11. axios.get('/user', {

  12. params: {

  13. ID: 12345

  14. }

  15. })

  16. .then(function (response) {

  17. console.log(response);

  18. })

  19. .catch(function (response) {

  20. console.log(response);

  21. });

发送一个 POST 请求

 
  1. axios.post('/user', {

  2. firstName: 'Fred',

  3. lastName: 'Flintstone'

  4. })

  5. .then(function (response) {

  6. console.log(response);

  7. })

  8. .catch(function (response) {

  9. console.log(response);

  10. });

发送多个并发请求

 
  1. function getUserAccount() {

  2. return axios.get('/user/12345');

  3. }

  4.  
  5. function getUserPermissions() {

  6. return axios.get('/user/12345/permissions');

  7. }

  8.  
  9. axios.all([getUserAccount(), getUserPermissions()])

  10. .then(axios.spread(function (acct, perms) {

  11. // Both requests are now complete

  12. }));

axios API

可以通过给 axios传递对应的参数来定制请求:

axios(config)

 
  1. // Send a POST request

  2. axios({

  3. method: 'post',

  4. url: '/user/12345',

  5. data: {

  6. firstName: 'Fred',

  7. lastName: 'Flintstone'

  8. }

  9. });

axios(url[, config])

 
  1. // Sned a GET request (default method)

  2. axios('/user/12345');

请求方法别名

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

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

注意

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

并发

处理并发请求的帮助方法

axios.all(iterable)

axios.spread(callback)

创建一个实例

你可以用自定义配置创建一个新的 axios 实例。

axios.create([config])

 
  1. var instance = axios.create({

  2. baseURL: 'https://some-domain.com/api/',

  3. timeout: 1000,

  4. headers: {'X-Custom-Header': 'foobar'}

  5. });

实例方法

所有可用的实例方法都列在下面了,指定的配置将会和该实例的配置合并。

axios#request(config)

axios#get(url[, config])

axios#delete(url[, config])

axios#head(url[, config])

axios#post(url[, data[, config]])

axios#put(url[, data[, config]])

axios#patch(url[, data[, config]])

请求配置

下面是可用的请求配置项,只有 url 是必需的。如果没有指定 method ,默认的请求方法是 GET

 
  1. {

  2. // `url` is the server URL that will be used for the request

  3. url: '/user',

  4.  
  5. // `method` is the request method to be used when making the request

  6. method: 'get', // default

  7.  
  8. // `baseURL` will be prepended to `url` unless `url` is absolute.

  9. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs

  10. // to methods of that instance.

  11. baseURL: 'https://some-domain.com/api/',

  12.  
  13. // `transformRequest` allows changes to the request data before it is sent to the server

  14. // This is only applicable for request methods 'PUT', 'POST', and 'PATCH'

  15. // The last function in the array must return a string or an ArrayBuffer

  16. transformRequest: [function (data) {

  17. // Do whatever you want to transform the data

  18.  
  19. return data;

  20. }],

  21.  
  22. // `transformResponse` allows changes to the response data to be made before

  23. // it is passed to then/catch

  24. transformResponse: [function (data) {

  25. // Do whatever you want to transform the data

  26.  
  27. return data;

  28. }],

  29.  
  30. // `headers` are custom headers to be sent

  31. headers: {'X-Requested-With': 'XMLHttpRequest'},

  32.  
  33. // `params` are the URL parameters to be sent with the request

  34. params: {

  35. ID: 12345

  36. },

  37.  
  38. // `paramsSerializer` is an optional function in charge of serializing `params`

  39. // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)

  40. paramsSerializer: function(params) {

  41. return Qs.stringify(params, {arrayFormat: 'brackets'})

  42. },

  43.  
  44. // `data` is the data to be sent as the request body

  45. // Only applicable for request methods 'PUT', 'POST', and 'PATCH'

  46. // When no `transformRequest` is set, must be a string, an ArrayBuffer or a hash

  47. data: {

  48. firstName: 'Fred'

  49. },

  50.  
  51. // `timeout` specifies the number of milliseconds before the request times out.

  52. // If the request takes longer than `timeout`, the request will be aborted.

  53. timeout: 1000,

  54.  
  55. // `withCredentials` indicates whether or not cross-site Access-Control requests

  56. // should be made using credentials

  57. withCredentials: false, // default

  58.  
  59. // `adapter` allows custom handling of requests which makes testing easier.

  60. // Call `resolve` or `reject` and supply a valid response (see [response docs](#response-api)).

  61. adapter: function (resolve, reject, config) {

  62. /* ... */

  63. },

  64.  
  65. // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.

  66. // This will set an `Authorization` header, overwriting any existing

  67. // `Authorization` custom headers you have set using `headers`.

  68. auth: {

  69. username: 'janedoe',

  70. password: 's00pers3cret'

  71. }

  72.  
  73. // `responseType` indicates the type of data that the server will respond with

  74. // options are 'arraybuffer', 'blob', 'document', 'json', 'text'

  75. responseType: 'json', // default

  76.  
  77. // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token

  78. xsrfCookieName: 'XSRF-TOKEN', // default

  79.  
  80. // `xsrfHeaderName` is the name of the http header that carries the xsrf token value

  81. xsrfHeaderName: 'X-XSRF-TOKEN', // default

  82.  
  83. // `progress` allows handling of progress events for 'POST' and 'PUT uploads'

  84. // as well as 'GET' downloads

  85. progress: function(progressEvent) {

  86. // Do whatever you want with the native progress event

  87. }

  88. }

响应的数据结构

响应的数据包括下面的信息:

 
  1. {

  2. // `data` is the response that was provided by the server

  3. data: {},

  4.  
  5. // `status` is the HTTP status code from the server response

  6. status: 200,

  7.  
  8. // `statusText` is the HTTP status message from the server response

  9. statusText: 'OK',

  10.  
  11. // `headers` the headers that the server responded with

  12. headers: {},

  13.  
  14. // `config` is the config that was provided to `axios` for the request

  15. config: {}

  16. }

当使用 then 或者 catch 时, 你会收到下面的响应:

 
  1. axios.get('/user/12345')

  2. .then(function(response) {

  3. console.log(response.data);

  4. console.log(response.status);

  5. console.log(response.statusText);

  6. console.log(response.headers);

  7. console.log(response.config);

  8. });

默认配置

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

全局 axios 默认配置

 
  1. axios.defaults.baseURL = 'https://api.example.com';

  2. axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

  3. axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

自定义实例默认配置

 
  1. // Set config defaults when creating the instance

  2. var instance = axios.create({

  3. baseURL: 'https://api.example.com'

  4. });

  5.  
  6. // Alter defaults after instance has been created

  7. 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.

 
  1. // Create an instance using the config defaults provided by the library

  2. // At this point the timeout config value is `0` as is the default for the library

  3. var instance = axios.create();

  4.  
  5. // Override timeout default for the library

  6. // Now all requests will wait 2.5 seconds before timing out

  7. instance.defaults.timeout = 2500;

  8.  
  9. // Override timeout for this request as it's known to take a long time

  10. instance.get('/longRequest', {

  11. timeout: 5000

  12. });

拦截器

你可以在处理 then 或 catch 之前拦截请求和响应

 
  1. // 添加一个请求拦截器

  2. axios.interceptors.request.use(function (config) {

  3. // Do something before request is sent

  4. return config;

  5. }, function (error) {

  6. // Do something with request error

  7. return Promise.reject(error);

  8. });

  9.  
  10. // 添加一个响应拦截器

  11. axios.interceptors.response.use(function (response) {

  12. // Do something with response data

  13. return response;

  14. }, function (error) {

  15. // Do something with response error

  16. return Promise.reject(error);

  17. });

移除一个拦截器:

 
  1. var myInterceptor = axios.interceptors.request.use(function () {/*...*/});

  2. axios.interceptors.request.eject(myInterceptor);

你可以给一个自定义的 axios 实例添加拦截器:

 
  1. var instance = axios.create();

  2. instance.interceptors.request.use(function () {/*...*/});

错误处理

 
  1. axios.get('/user/12345')

  2. .catch(function (response) {

  3. if (response instanceof Error) {

  4. // Something happened in setting up the request that triggered an Error

  5. console.log('Error', response.message);

  6. } else {

  7. // The request was made, but the server responded with a status code

  8. // that falls out of the range of 2xx

  9. console.log(response.data);

  10. console.log(response.status);

  11. console.log(response.headers);

  12. console.log(response.config);

  13. }

  14. });

Promises

axios 依赖一个原生的 ES6 Promise 实现,如果你的浏览器环境不支持 ES6 Promises,你需要引入 polyfill

TypeScript

axios 包含一个 TypeScript 定义

/// <reference path="axios.d.ts" />
import * as axios from 'axios';
axios.get('/user?ID=12345');

一、vue-resource
1、引入资源方式
1)下载vue-resource.js,添加到项目中
2)CDN:http://www.bootcdn.cn/vue-resource/
3)npm install vue-resource 即可 。然后在main.js中配置import VueResource from ‘vue-resource’; 然后用Vue.use(VueResource) 方法启用插件。
2、使用$http,直接封装在methods中
1)get方式

this.$http.get('url',{
        param1:value1,  
        param2:value2  
    }).then(function(response){  
        // response.data中获取ResponseData实体
    },function(response){  
        // 发生错误
    });

2)post方式

this.$http.post('url',{  
        param1:value1,  
        param2:value2  
    },{  
        emulateJSON:true  
    }).then(function(response){  
        // response.data中获取ResponseData实体
    },function(response){  
        // 发生错误
    });

注:put、delete类似

二、axios
1、引入资源方式
1)下载axios.min.js,添加到项目中
2)使用CDN:
3)npm方式: npm install axios
2、使用axios,直接封装在methods中
1)get方式

axios.get('url', {
        params: {
            param1: value1,
            param2:value2
        }
    }).then(function (response) {
        // response.data中获取ResponseData实体
    }).catch(function (error) {
        // 发生错误
    });

2)post方式:默认json格式

axios.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
    }).then(function (response) {
        // response.data中获取ResponseData实体
    }).catch(function (error) {
        // 发生错误
    });

注:put、delete类似

三、ajax
1、引入资源方式
1)下载jquery.min.js,添加到项目中 http://jquery.com/download/
2)使用CDN:
https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js
https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js
http://upcdn.b0.upaiyun.com/libs/jquery/jquery-2.0.2.min.js
http://lib.sinaapp.com/js/jquery/2.0.2/jquery-2.0.2.min.js
http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
http://ajax.htmlnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js
2、使用方式,直接封装在method中

$.ajax({
    url:'url',
    type:'POST', //GET、PUT、DELETE
    async:true,    //是否异步
    data:{
        name:'zhang',
        age:28
    },
    timeout:5000,    //超时时间
    dataType:'json',    //返回的数据格式:json/xml/html/script/jsonp/text
    beforeSend:function(xhr){
        // 发送前处理
    },
    success:function(data,textStatus,jqXHR){
        // 调用成功,解析response中的data到自定义的data中
    },
    error:function(xhr,textStatus){
        // 调用时,发生错误
    },
    complete:function(){
        // 交互后处理
    }
})

猜你喜欢

转载自blog.csdn.net/qq_36663951/article/details/82686906