記錄一次axios的封裝

直接上代碼吧,大牛勿噴ios


import axios from 'axios'import config from '../config'
class Axios {  // 構造函數  constructor() {    this.headers = {'Content-Type': 'application/json;charset=UTF-8'}    this.baseURL = config.baseURL  }
  /**   * @param options  options包含(method,url,params,headers,baseURL)   * @returns {Promise}   */  request (options) {    const {      headers,      baseURL    } = options    return new Promise((resolve, reject) => {      if (headers) {        this.headers = headers      }      if (baseURL) {        this.baseURL = baseURL      }      // if (method.toLocaleLowerCase() !== 'get') {      //   options.params = qs.stringify(params)      // }      const instance = axios.create({        baseURL: this.baseURL,        timeout: 5000,        headers: this.headers      })
      instance(options).then(response => {        const res = response.data        resolve(res)      }).catch(error => {        reject(error)      })    })  }
  // get 請求方法  get(url, params, headers, baseURL) {    return this.request({method: 'GET', url, params, headers, baseURL})  }
  //post 請求方法  post(url, params, headers, baseURL) {    return this.request({method: 'POST', url, params, headers, baseURL})  }}
export default new Axios()

複製代碼
相關文章
相關標籤/搜索