vue要求axios二次パッケージ

31811 ワード

vue要求axios二次パッケージ
  • ネットワーク要求の共通項
  • を構成する.
  • インタフェース要求失敗、異常に対する統一処理
  • パッケージaxios
  • 完全なコードファイル
  • ネットワーク要求の共通項目の構成
    インタフェースリクエストのタイムアウト時間、ヘッダなど、通常、いくつかのビジネスに遭遇します.axiosではrequestブロッキングが提供する.対応するコールバック関数では,対応する業務に応じて処理すればよい.
    
    import axios from 'axios'
    
    axios.interceptors.request.use((config) => {
     //             
      return config
    }, (err) => {
      //               
      return Promise.resolve(err)
    })
    

    インタフェースリクエストの失敗、例外の統一処理
    
    axios.interceptors.response.use((data) => {
      //         
      return data
    }, (err) => {
       //            
      if (err.response.status === 504 || err.response.status === 404) {
        alert('      ')
      } else if (err.response.status === 403) {
        alert('    ,      ')
      } else {
        alert('    ')
      }
      return Promise.resolve(err)
    })
    
    

    パッケージaxios
    xiosでは様々なパラメータ構成が提供されています.次に、開発したツールの一部をパッケージします.
    {
      //       
      url: '/user',
    
      //       ,   get
      method: 'get', // default
    
      //  url         ,        url  。    
      baseURL: 'https://some-domain.com/api/',
    
      //               POST PUT  PATCH
      transformRequest: [function (data, headers) {
        // Do whatever you want to transform the data
    
        return data;
      }],
    
      //          
      // it is passed to then/catch
      transformResponse: [function (data) {
        // Do whatever you want to transform the data
    
        return data;
      }],
    
      //       
      headers: {'X-Requested-With': 'XMLHttpRequest'},
    
     //     
      params: {
        ID: 12345
      },
    
      //           
      paramsSerializer: function(params) {
        return Qs.stringify(params, {arrayFormat: 'brackets'})
      },
     //     
       data: {
        firstName: 'Fred'
      },
    
      //     
      timeout: 1000,
    
      //     
        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) {
        /* ... */
      },
    
      //         jira 
      auth: {
        username: 'janedoe',
        password: 's00pers3cret'
      },
    
      //           
      responseType: 'json', // 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 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
    
      // `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
      // 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) {
      })
    }
    
    

    完全なコードファイル
    https.jsファイルコード
    
    /**
     * Created by BruceLv on 2018/1/22.
     */
    import axios from 'axios'
    
    let base = 'https://httpbin.org/'
    
    axios.interceptors.request.use((config) => {
      return config
    }, (err) => {
      alert('    ')
      return Promise.resolve(err)
    })
    
    
    axios.interceptors.response.use((data) => {
      //         
      return data
    }, (err) => {
       //         
      if (err.response.status === 504 || err.response.status === 404) {
        alert('      ')
      } else if (err.response.status === 403) {
        alert('    ,      ')
      } else {
        alert('    ')
      }
      return Promise.resolve(err)
    })
    
    
    export function postRequest(url, params) {
      return axios({
        method: 'post',
        url: `${base}${url}`,
        data: params,
        transformRequest: [function (data) {
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret
        }],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
    }
    
    export function uploadFileRequest(url, params) {
      return axios({
        method: 'post',
        url: `${base}${url}`,
        data: params,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
    }
    
    export function putRequest(url, params) {
      return axios({
        method: 'put',
        url: `${base}${url}`,
        data: params,
        transformRequest: [function (data) {
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret
        }],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
    }
    
    export function deleteRequest(url) {
      return axios({
        method: 'delete',
        url: `${base}${url}`
      })
    }
    
    export function getRequest(url) {
      return axios({
        method: 'get',
        url: `${base}${url}`
      })
    }