axios api 文档

  1  https://github.com/axios/axios
  2     axios API
  3     为方便起见,为所有支持的请求方法提供了别名,在使用别名方法时, url、method、data 这些属性都不必在配置中指定。
  4 
  5     axios.request(config)
  6     axios.get(url[, config])
  7     axios.delete(url[, config])
  8     axios.head(url[, config])
  9     axios.post(url[, data[, config]])
 10     axios.put(url[, data[, config]])
 11     axios.patch(url[, data[, config]])
 12 
 13     并发
 14     axios.all(iterable)
 15     axios.spread(callback)
 16 
 17     创建实例
 18     const instance =  axios.create([config])
 19 
 20 
 21     实例方法,,以下是可用的实例方法。指定的配置将与实例的配置合并
 22     axios#request(config)
 23     axios#get(url[, config])
 24     axios#delete(url[, config])
 25     axios#head(url[, config])
 26     axios#post(url[, data[, config]])
 27     axios#put(url[, data[, config]])
 28     axios#patch(url[, data[, config]])
 29     instance({config})
 30 
 31     这些是创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method,请求将默认使用 get 方法。
 32     {
 33         // 是用于请求的服务器 URL
 34         url:'',
 35         //是创建请求时使用的方法,默认是 get
 36         method:'',
 37         // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
 38         baseURL:'',
 39         // `transformRequest` 允许在向服务器发送前,修改请求数据,只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
 40         // // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
 41         transformRequest:[function(data,headers){
 42             // 对 data 进行任意转换处理
 43             return  data;
 44         }],
 45         // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
 46         transformResponse:[function(data){
 47 
 48             return data;
 49         }],
 50         // `headers` 是即将被发送的自定义请求头
 51         headers: {
 52             'X-Requested-With': 'XMLHttpRequest'
 53         },
 54         // `params` 是即将与请求一起发送的 URL 参数
 55         // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
 56          params: {
 57             ID: 12345
 58          },
 59          // `paramsSerializer` 是一个负责 `params` 序列化的函数
 60          paramsSerializer: function (params) {
 61             return Qs.stringify(params, {arrayFormat: 'brackets'})
 62          },
 63           // `data` 是作为请求主体被发送的数据
 64           // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
 65           // 在没有设置 `transformRequest` 时,必须是以下类型之一:
 66           // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
 67           // - 浏览器专属:FormData, File, Blob
 68           // - Node 专属: Stream
 69          data: {
 70             firstName: 'Fred'
 71          },
 72          // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
 73          // 如果请求话费了超过 `timeout` 的时间,请求将被中断
 74          timeout: 1000,
 75 
 76          // `withCredentials` 表示跨域请求时是否需要使用凭证
 77          withCredentials: false, // 默认的
 78 
 79 
 80         // `adapter` 允许自定义处理请求,以使测试更轻松
 81         // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
 82         adapter: function (config) {
 83     .
 84         },
 85         // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
 86         // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
 87         //请注意,只能通过此参数配置HTTP Basic身份验证。
 88         //对于Bearer令牌等,请改用`Authorization`自定义标头。
 89         auth: {
 90             username: 'janedoe',
 91             password: 's00pers3cret'
 92         },
 93         // `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
 94         responseType: 'json', // 默认的
 95 
 96         // `responseEncoding`表示用于解码响应的编码
 97         // 注意:忽略“ stream”或客户端请求的“ responseType”
 98         responseEncoding: 'utf8', // 默认的
 99 
100         // xsrfCookieName是cookie的名称,用作xsrf令牌的值
101         xsrfCookieName: 'XSRF-TOKEN', // default
102 
103         // `xsrfHeaderName` 是承载 xsrf token 的值的 HTTP 头的名称
104         xsrfHeaderName: 'X-XSRF-TOKEN', // 默认的
105 
106         // `onUploadProgress` 允许为上传处理进度事件
107         onUploadProgress: function (progressEvent) {
108             // 对原生进度事件的处理
109         },
110 
111         // `onDownloadProgress` 允许为下载处理进度事件
112         onDownloadProgress: function (progressEvent) {
113             // 对原生进度事件的处理
114         },
115          // `maxContentLength` 定义允许的响应内容的最大尺寸
116         maxContentLength: 2000,
117 
118         // // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。
119         // 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
120          validateStatus: function (status) {
121             return status >= 200 && status < 300; // 默认的
122          },
123         // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
124         // 如果设置为0,将不会 follow 任何重定向
125         maxRedirects: 5, // 默认的
126 
127         // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
128         // `keepAlive` 默认没有启用
129 
130         httpAgent: new http.Agent({ keepAlive: true }),
131         httpsAgent: new https.Agent({ keepAlive: true }),
132 
133         // 'proxy' 定义代理服务器的主机名称和端口
134         // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
135         // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
136         proxy: {
137             host: '127.0.0.1',
138             port: 9000,
139             auth: : {
140               username: 'mikeymike',
141               password: 'rapunz3l'
142             }
143         },
144     }
145 
146     //  响应结构
147     {
148       // `data` 由服务器提供的响应
149       data: {},
150       // `status` 来自服务器响应的 HTTP 状态码
151       status: 200,
152       // `statusText` 来自服务器响应的 HTTP 状态信息
153       statusText: 'OK',
154       // `headers` 服务器响应的头
155       headers: {},
156       // `config` 是为请求提供的配置信息
157       config: {}
158     }
159 
160     全局的 axios 默认值
161     axios.defaults.baseURL = 'https://api.example.com';
162     axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
163 
164     自定义实例默认值
165     // 创建实例时设置配置的默认值
166     var instance = axios.create({
167       baseURL: 'https://api.example.com'
168     });
169 
170     // 在实例已创建后修改默认值
171     axios.defaults.baseURL = 'https://api.example.com';
172     instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
173 
174     配置的优先顺序
175     var instance = axios.create();
176 
177     instance.defaults.timeout = 2500;
178 
179     instance.get('/longRequest', {
180         timeout: 5000
181     });
182 
183 
184     拦截器
185     在请求或响应被 then 或 catch 处理前拦截它们。
186 
187     // 添加请求拦截器
188     axios.interceptors.request.use(function (config) {
189         // 在发送请求之前做些什么
190         return config;
191      }, function (error) {
192         // 对请求错误做些什么
193         return Promise.reject(error);
194      });
195 
196     // 添加响应拦截器
197     axios.interceptors.response.use(function (response) {
198       // 对响应数据做点什么
199       return response;
200     }, function (error) {
201       // 对响应错误做点什么
202       return Promise.reject(error);
203     });
204 
205     如果你想在稍后移除拦截器,可以这样:
206     var myInterceptor = axios.interceptors.request.use(function () { ....});
207     axios.interceptors.request.eject(myInterceptor);
208 
209 
210     可以为自定义 axios 实例添加拦截器
211     var instance = axios.create();
212     instance.interceptors.request.use(function () {.../});
213 
214 
215     执行多个并发请求
216     function getUserAccount() {
217         return axios.get('/user/12345');
218     }
219     function getUserPermissions() {
220         return axios.get('/user/12345/permissions');
221     }
222     axios.all([getUserAccount(), getUserPermissions()])
223      .then(axios.spread(function (acct, perms) {
224           // 两个请求现在都执行完成
225     }));
226 
227     // 取消请求
228     方法一:
229     var CancelToken = axios.CancelToken;
230     var source = CancelToken.source();
231 
232     axios.get('/user/12345', {
233       cancelToken: source.token
234     }).catch(function(thrown) {
235       if (axios.isCancel(thrown)) {
236         console.log('Request canceled', thrown.message);
237       } else {
238         // 处理错误
239       }
240     });
241 
242     // 取消请求(message 参数是可选的)
243     source.cancel('Operation canceled by the user.');
244 
245 
246     方法二:
247     var CancelToken = axios.CancelToken;
248     var cancel;
249 
250     axios.get('/user/12345', {
251       cancelToken: new CancelToken(function executor(c) {
252         // executor 函数接收一个 cancel 函数作为参数
253         cancel = c;
254       })
255     });
256     // 取消请求
257     cancel();

 

posted @ 2020-02-28 18:34  kgwei  阅读(994)  评论(0编辑  收藏  举报