vux ajax請求 及 跨域

1)使用 AjaxPlugin 插件(在組件裏使用)node

引入插件api

import { AjaxPlugin } from 'vux'

初始化跨域

export default {
  components: {
    AjaxPlugin
  },
  data () {
    return {
    }
  }
}

封閉一個方法方便調用(正式使用時,你應該還須要計算簽名之類的操做)函數

function htttpRequest (url, params, cb) {
  let dataStr = ''
  for (let key in params) {
    dataStr += key + '=' + params[key]
  }
  dataStr = dataStr.substr(0, dataStr.length - 1)

  AjaxPlugin.$http.post(url, dataStr)
  .then((response) => {
    if (cb) cb(response.data)
  })
}

 使用示例post

export default {
  components: {
    AjaxPlugin
  },
  data () {
    return {
      articleList: this.getArticleList(1)
    }
  },
  methods: {
    getArticleList: function (catId) {
      let _this = this

      htttpRequest('/api', {method: 'article.getList', 'catId': catId}, function (data) {
        _this.articleList = data.Result.ArticleList
      })
      return []
    }
  }
}

這裏示例寫的是初始化時,默認調用一次,你能夠在相應的按鈕上點擊事件再調用此函數this

 

2)關於跨域(用nodejs代理轉發請求)url

若是你有注意,應該會發現,上面請求寫的 url 是 '/api' ,這不是一條確切的接口地址,假設你的域名爲 http://localhost:8080,那麼它請求的地址即爲 http://localhost:8080/apispa

這個 /api 默認是不存在的,如今咱們配置一下 nodejs ,讓它爲咱們轉發請求插件

 

假設,我須要請求的接口的入口爲 http://www.xxx.com/api代理

修改 /config/index.js 配置文件,修改 dev 選項下 proxyTable 的值爲以下

proxyTable: {
    '/api': {
        target: 'http://www.xxx.com/',
        changeOrigin: true
    }
},

PS:這裏使用的是一個叫 http-proxy-middleware 的 nodejs 中間件,系統已默認爲咱們集成,直接配置就行了

上面的配置的意思是:遇到以 '/api'開關的 http 請求,自動轉化到 target (目標)url 地址去,實際請求地址就是 target + '/api'

 

須要注意的是,假設,你須要請求的接口的入口爲 http://www.xxx.com/rest,而代碼裏請求的 url 寫的是 '/api',則你須要使用 pathRewrite 來進行路徑重寫,而不是直接改 traget

proxyTable: {
    '/api': {
        target: 'http://www.xxx.com/',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/rest'
        }
    }
},

 

下面是一個錯誤示範

proxyTable: {
    '/api': {
        target: 'http://www.xxx.com/rest',
        changeOrigin: true
    }
},

這裏實際請求的地址爲:http://www.xxx.com/rest/api,很明顯是錯誤的(固然,你也能夠使用 pathRewrite 把 '/api' 改爲 '',也是能夠的)

 


相關文章
相關標籤/搜索