axios和promise

什麼是axios

axios is a promise based HTTP client for the browser and node.js前端

Features:node

  • 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’)後調用apijquery

//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:ios

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 requestsgit

第二種使用實例化了的對象github

axios.create([config])web

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

Instance methods:docker

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

instance({ url: '/info/devices/', method: 'get' });

Request Config

 好大一篇,好些我都沒有用到,也不能明確知道它是幹 什麼用,有待慢慢的展開學習。json

{ 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對象形式使用。

相關文章
相關標籤/搜索