Vue前后端數據交互、代理轉發,response公共處理


1.前后台交互

  Vue前后端交互可以通過下面兩種方式實現;

  方式1:通過vue-resource中

this.$http.post('/api/sys/login/getPasskey.do',{
          keytype:'SESSION_PASSKEY'
        }).then(function(res){
          alert(res.data);

        },function(res){
          alert(res.status)
        });

  方式2:通過axios

axios.doPost('/api/sys/login/getPasskey.do',{
          keytype:'SESSION_PASSKEY'
        }).then(function(res){
          alert(res.data);

        },function(res){
          alert(res.status)
        });

  這件建議使用方式2;

這里對方式2進行了封裝,詳細如下:

  目錄結構:

  文件:代碼如下

/**
 * Created by Zl on 2019/4/14.
 */
import axios from 'axios'

export default {

  httpMethod: {
    GET: 'get',
    POST: 'post',
    PUT: 'put',
    DELETE: 'delete'
  },

  instance: axios.create({
    baseURL: '/api',
    timeout: 10000,
  }),


  /**
   *
   * @param url
   * @param pathParams
   * @param options
   * @returns {*|Promise}
   */
  doGet(url, pathParams = null, options = null) {
    return this.doRequest(url, this.httpMethod.GET, pathParams, null, options)
  },

  /**
   * Http Post
   * @param url
   * @param pathParams
   * @param body
   * @param options
   * @returns {*|Promise}
   */
  doPost(url, pathParams = null, body = null, options = null) {
    return this.doRequest(url, this.httpMethod.POST, pathParams, body, options)
  },

  /**
   * Http Put
   * @param url
   * @param pathParams
   * @param body
   * @param options
   * @returns {*|Promise}
   */
  doPut(url, pathParams = null, body = null, options = null) {
    return this.doRequest(url, this.httpMethod.PUT, pathParams, body, options)
  },

  /**
   * Http Delete
   * @param url
   * @param pathParams
   * @param options
   * @returns {*|Promise}
   */
  doDelete(url, pathParams = null, options = null) {
    return this.doRequest(url, this.httpMethod.DELETE, pathParams, null, options)
  },

  /**
   * Http Request
   * @param url
   * @param method
   * @param pathParams
   * @param body
   * @param options
   * @returns {Promise}
   */
  doRequest(url, method, pathParams, body, options) {
    let wrapURL = this._wrapUrl(url, pathParams)
    let request = null
    switch (method) {
      case this.httpMethod.GET: {
        if (options !== null) {
          request = this.instance.get(wrapURL, {params: options})
        } else {
          request = this.instance.get(wrapURL)
        }
        break
      }
      case this.httpMethod.POST: {
        request = this.instance.post(wrapURL, body, options)
        break
      }
      case this.httpMethod.PUT: {
        request = this.instance.put(wrapURL, body, options)
        break
      }
      case this.httpMethod.DELETE: {
        request = this.instance.delete(wrapURL, options)
        break
      }
    }
    return this._requestPromise(request)
  },

  /**
   * Request Promise
   * @param request {Promise} Axios Http Promise
   * @returns {Promise}
   * @private
   */
  _requestPromise(request) {
    return new Promise(function (resolve, reject) {
      request.then(response => {
        if (response.data.status === 0) {
          resolve(response.data)
        } else {
          reject(response.data.message)
        }
      }, error => {
        reject(error)
      })
    })
  },

  /**
   * 從URL匹配出參數pathParams
   * @param {string} url
   * @param {object} params
   * @returns {string}
   * @private
   */
  _wrapUrl(url, params) {
    if (params !== null) {
      let matches = this._getMatches(url)
      for (let match of matches) {
        let value = params[match.replace(':', '')]
        if (value !== null) {
          url = url.replace(match, value)
        }
      }
    }
    return url
  },

  /**
   * 正則Group匹配
   * @param {string} string
   * @returns {Array}
   * @private
   */
  _getMatches(string) {
    let matches = []
    let regex = /(:[a-z_A-Z]+)/
    let match = regex.exec(string)
    while (match !== null) {
      matches.push(match[1])
      string = string.replace(match[1], '')
      match = regex.exec(string)
    }
    return matches
  }
}

  使用方式:

     

 2.配置轉發  

  通過前端用的服務域名和端口和后台並不是同一個,比如前端是localhost:4200,后端是localhost:8080,這時候需要將前端的請求到8080上,這時候就需要使用轉發;配置如下:

  

  

proxyTable: {
      '/api': {
        target: 'http://localhost:8089', // 接口的域名
        // secure: false,  // 如果是https接口,需要配置這個參數
        changeOrigin: false, // 如果接口跨域,需要進行這個參數配置,為true的話,請求的header將會設置為匹配目標服務器的規則(Access-Control-Allow-Origin)
        pathRewrite: {
          '^/api': '' //本身的接口地址沒有 '/api' 這種通用前綴,所以要rewrite,如果本身有則去掉
        }
      }
    },

  即對所有以api開頭的請求進行轉發到localhost:8089上,同時去掉api前綴;

  轉發前請求路徑:localhost:4209/api/sys/admin/getPassKey.do;配置后路徑:localhost:8089/sys/admin/getPassKey.do

 3. response公共處理


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM