axios和promise
什么是axios
axios is a promise based HTTP client for the browser and node.js
Features:
- Make XMLHttpRequests from the browser
- Make http requests from node.js
- Supports the Promise API
- Intercept request and response
- Transform request and response data
- Cancel requests
- Automatic transforms for JSON data
- Client side support for protecting against XSRF
使用方式有两种
第一种,直接 const axios = require(‘axioa’)后调用api
//Two ways to Send a POST request axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
api:
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.all(iterable)
axios.spread(callback)
后两个方法用于处理concurrent requests
第二种使用实例化了的对象
axios.create([config])
const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
Instance methods:
request(config)
get(url[, config])
delete(url[, config])
head(url[, config])
options(url[, config])
post(url[, data[, config]])
put(url[, data[, config]])
patch(url[, data[, config]])
getUri([config])
个人觉得这种特别适用于有很多的service api调用的时候,这样可以统一配置请求的url,如baseURL;
instance({ url: '/info/devices/', method: 'get' });
Request Config
好大一篇,好些我都没有用到,也不能明确知道它是干 什么用,有待慢慢的展开学习。
{ url: '/user', method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', and 'PATCH' // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, // FormData or Stream // You may modify the headers object. transformRequest: [function (data, headers) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object // what is a URLSearchParams object // var paramsString = "q=URLUtils.searchParams&topic=api"; // var searchParams = new URLSearchParams(paramsString); params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', and 'PATCH' // When no `transformRequest` is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, timeout: 1000, // default is `0` (no timeout) // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Return a promise and supply a valid response (see lib/adapters/README.md). adapter: function (config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` indicates the type of data that the server will respond with // options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` allows handling of progress events for downloads onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content in bytes allowed maxContentLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' defines the hostname and port of the proxy server. // You can also define your proxy using the conventional `http_proxy` and // `https_proxy` environment variables. If you are using environment variables // for your proxy configuration, you can also define a `no_proxy` environment // variable as a comma-separated list of domains that should not be proxied. // Use `false` to disable proxies, ignoring environment variables. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and // supplies credentials. // This will set an `Proxy-Authorization` header, overwriting any existing // `Proxy-Authorization` custom headers you have set using `headers`. proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }) }
可以通过defaults属性来取得request config里各项的值,还可以重新赋值
更改全局的axios的defaults
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';
更改某个实例的defaults
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Response Schema
{ data: {}, status: 200, 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: {} }
当出错时,会进入catch进行错误处理
axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); });
配置response.status是多少时,触发reject
axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Reject only if the status code is greater than or equal to 500 } })
Interceptors
重头戏在最后了
You can intercept requests or responses before they are handled by then
or catch
.
还是两种途径,全局加、单例加
只展示单例加interceptors的代码吧,可以在这里统一的出处理一些事件,只让前端观注view
const instance= axios.create({ baseURL: 'http://somedomain.com/api/', timeout: 300000 }) // request interceptors instance.interceptors.request.use(config => { //发送请求前,头部加上token值 if (store.getters.token && config.url !== '/login') { config.headers.common['Authorization'] = ['Bearer', getToken()].join(' '); } else { config.headers.common['Authorization'] = ''; } return config }, error => { Promise.reject(error) }) // respone interceptor instance.interceptors.response.use( response => response, error => { let msg= ''; if (error.response && error.response.status) { const status = error.response.status; switch (status) { case 401: router.replace({ path: '/' }); break; default: break; } } if (!error.response) { msg = '访问超时'; } console.log(msg ); return Promise.reject(msg); })
什么是promise
在调用一个不能立即返回结果的方法或耗时很长的方法时,promise可以帮助在方法有返回值时返回,用resolve和reject来处理返回结果。
new Promise( function(resolve, reject) {...} /* executor */ );
它有三个状态: pending ,fulfilled, rejected。
resolve对应执行then的参数function.
reject对应执行catch的参数function.
它可以用来配合axios, setTimeout一起使用。
var pro = new Promise((resolve, reject) => { axios.get({ url:'http://website.com/api/data' }).then(response => { resolve(response.data); }).catch(error => { reject(error); }) }); pro.then(data=>{ console.log(data); }).catch(error=>{ console.log(error); });
promise还有两个方法,Promise.all / Promise.race
Promise.all(iterable)这个方法返回一个新的promise对象,该promise对象在iterable参数对象里所有的promise对象都成功的时候才会触发成功,一旦有任何一个iterable里面的promise对象失败则立即触发该promise对象的失败。这个新的promise对象在触发成功状态以后,会把一个包含iterable里所有promise返回值的数组作为成功回调的返回值,顺序跟iterable的顺序保持一致;如果这个新的promise对象触发了失败状态,它会把iterable里第一个触发失败的promise对象的错误信息作为它的失败错误信息。Promise.all方法常被用于处理多个promise对象的状态集合
Promise.race(iterable)当iterable参数里的任意一个子promise被成功或失败后,父promise马上也会用子promise的成功返回值或失败详情作为参数调用父promise绑定的相应句柄,并返回该promise对象。
通常而言,如果你不知道一个值是否是Promise对象,使用Promise.resolve(value) 来返回一个Promise对象,这样就能将该value以Promise对象形式使用。