不再继续维护vue-resource,并推荐大家使用 axios 开始,axios 被越来越多的人所了解。

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

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

执行GET请求

 1     // 向具有指定ID的用户发出请求
 2     axios.get('/user?ID=12345')
 3     .then(function (response) {
 4     console.log(response);
 5     })
 6     .catch(function (error) {
 7     console.log(error);
 8     });
 9      
10     // 也可以通过 params 对象传递参数
11     axios.get('/user', {
12     params: {
13     ID: 12345
14     }
15     })
16     .then(function (response) {
17     console.log(response);
18     })
19     .catch(function (error) {
20     console.log(error);
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 (error) {
 9     console.log(error);
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     //两个请求现已完成
12     }));    

axios API
可以通过将相关配置传递给 axios 来进行请求。

 1 axios(config)    
 2     // 发送一个 POST 请求
 3     axios({
 4     method: 'post',
 5     url: '/user/12345',
 6     data: {
 7     firstName: 'Fred',
 8     lastName: 'Flintstone'
 9     }
10     });    
11 axios(url[, config])
12     // 发送一个 GET 请求 (GET请求是默认请求模式)
13     axios('/user/12345');

请求方法别名

  1 为了方便起见,已经为所有支持的请求方法提供了别名。
  2     axios.request(config)
  3     axios.get(url [,config])
  4     axios.delete(url [,config])
  5     axios.head(url [,config])
  6     axios.post(url [,data [,config]])
  7     axios.put(url [,data [,config]])
  8     axios.patch(url [,data [,config]])    
  9 注意
 10     当使用别名方法时,不需要在config中指定url,method和data属性。
 11 
 12 并发
 13     帮助函数处理并发请求。
 14 
 15     axios.all(iterable)
 16     axios.spread(callback)
 17 创建实例
 18     您可以使用自定义配置创建axios的新实例。
 19     axios.create([config])
 20     var instance = axios.create({
 21     baseURL: 'https://some-domain.com/api/',
 22     timeout: 1000,
 23     headers: {'X-Custom-Header': 'foobar'}
 24     });
 25 实例方法
 26     可用的实例方法如下所示。 指定的配置将与实例配置合并。
 27 
 28     axios#request(config)
 29     axios#get(url [,config])
 30     axios#delete(url [,config])
 31     axios#head(url [,config])
 32     axios#post(url [,data [,config]])
 33     axios#put(url [,data [,config]])
 34     axios#patch(url [,data [,config]])
 35 
 36 请求配置
 37 这些是用于发出请求的可用配置选项。 只有url是必需的。 如果未指定方法,请求将默认为GET。
 38     {
 39     // `url`是将用于请求的服务器URL
 40     url: '/user',
 41      
 42     // `method`是发出请求时使用的请求方法
 43     method: 'get', // 默认
 44      
 45     // `baseURL`将被添加到`url`前面,除非`url`是绝对的。
 46     // 可以方便地为 axios 的实例设置`baseURL`,以便将相对 URL 传递给该实例的方法。
 47     baseURL: 'https://some-domain.com/api/',
 48      
 49     // `transformRequest`允许在请求数据发送到服务器之前对其进行更改
 50     // 这只适用于请求方法'PUT''POST''PATCH'
 51     // 数组中的最后一个函数必须返回一个字符串,一个 ArrayBuffer或一个 Stream
 52      
 53     transformRequest: [function (data) {
 54     // 做任何你想要的数据转换
 55      
 56     return data;
 57     }],
 58      
 59     // `transformResponse`允许在 then / catch之前对响应数据进行更改
 60     transformResponse: [function (data) {
 61     // Do whatever you want to transform the data
 62      
 63     return data;
 64     }],
 65      
 66     // `headers`是要发送的自定义 headers
 67     headers: {'X-Requested-With': 'XMLHttpRequest'},
 68      
 69     // `params`是要与请求一起发送的URL参数
 70     // 必须是纯对象或URLSearchParams对象
 71     params: {
 72     ID: 12345
 73     },
 74      
 75     // `paramsSerializer`是一个可选的函数,负责序列化`params`
 76     // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
 77     paramsSerializer: function(params) {
 78     return Qs.stringify(params, {arrayFormat: 'brackets'})
 79     },
 80      
 81     // `data`是要作为请求主体发送的数据
 82     // 仅适用于请求方法“PUT”,“POST”和“PATCH”
 83     // 当没有设置`transformRequest`时,必须是以下类型之一:
 84     // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
 85     // - Browser only: FormData, File, Blob
 86     // - Node only: Stream
 87     data: {
 88     firstName: 'Fred'
 89     },
 90      
 91     // `timeout`指定请求超时之前的毫秒数。
 92     // 如果请求的时间超过'timeout',请求将被中止。
 93     timeout: 1000,
 94      
 95     // `withCredentials`指示是否跨站点访问控制请求
 96     // should be made using credentials
 97     withCredentials: false, // default
 98      
 99     // `adapter'允许自定义处理请求,这使得测试更容易。
100     // 返回一个promise并提供一个有效的响应(参见[response docs](#response-api))
101     adapter: function (config) {
102     /* ... */
103     },
104      
105     // `auth'表示应该使用 HTTP 基本认证,并提供凭据。
106     // 这将设置一个`Authorization'头,覆盖任何现有的`Authorization'自定义头,使用`headers`设置。
107     auth: {
108     username: 'janedoe',
109     password: 's00pers3cret'
110     },
111      
112     // “responseType”表示服务器将响应的数据类型
113     // 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
114     responseType: 'json', // default
115      
116     //`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名称
117     xsrfCookieName: 'XSRF-TOKEN', // default
118      
119     // `xsrfHeaderName`是携带xsrf令牌值的http头的名称
120     xsrfHeaderName: 'X-XSRF-TOKEN', // default
121      
122     // `onUploadProgress`允许处理上传的进度事件
123     onUploadProgress: function (progressEvent) {
124     // 使用本地 progress 事件做任何你想要做的
125     },
126      
127     // `onDownloadProgress`允许处理下载的进度事件
128     onDownloadProgress: function (progressEvent) {
129     // Do whatever you want with the native progress event
130     },
131      
132     // `maxContentLength`定义允许的http响应内容的最大大小
133     maxContentLength: 2000,
134      
135     // `validateStatus`定义是否解析或拒绝给定的promise
136     // HTTP响应状态码。如果`validateStatus`返回`true`(或被设置为`null` promise将被解析;否则,promise将被
137       // 拒绝。
138     validateStatus: function (status) {
139     return status >= 200 && status < 300; // default
140     },
141      
142     // `maxRedirects`定义在node.js中要遵循的重定向的最大数量。
143     // 如果设置为0,则不会遵循重定向。
144     maxRedirects: 5, // 默认
145      
146     // `httpAgent`和`httpsAgent`用于定义在node.js中分别执行http和https请求时使用的自定义代理。
147     // 允许配置类似`keepAlive`的选项,
148     // 默认情况下不启用。
149     httpAgent: new http.Agent({ keepAlive: true }),
150     httpsAgent: new https.Agent({ keepAlive: true }),
151      
152     // 'proxy'定义代理服务器的主机名和端口
153     // `auth`表示HTTP Basic auth应该用于连接到代理,并提供credentials。
154     // 这将设置一个`Proxy-Authorization` header,覆盖任何使用`headers`设置的现有的`Proxy-Authorization` 自定义 headers。
155     proxy: {
156     host: '127.0.0.1',
157     port: 9000,
158     auth: : {
159     username: 'mikeymike',
160     password: 'rapunz3l'
161     }
162     },
163      
164     // “cancelToken”指定可用于取消请求的取消令牌
165     // (see Cancellation section below for details)
166     cancelToken: new CancelToken(function (cancel) {
167     })
168     }
169 使用 then 时,您将收到如下响应:
170     axios.get('/user/12345')
171     .then(function(response) {
172     console.log(response.data);
173     console.log(response.status);
174     console.log(response.statusText);
175     console.log(response.headers);
176     console.log(response.config);
177     });
View Code

相关文章: