1)使用 AjaxPlugin 插件(在組件里使用)
引入插件
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) }) }
使用示例
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 [] } } }
這里示例寫的是初始化時,默認調用一次,你可以在相應的按鈕上點擊事件再調用此函數
2)關於跨域(用nodejs代理轉發請求)
如果你有注意,應該會發現,上面請求寫的 url 是 '/api' ,這不是一條確切的接口地址,假設你的域名為 http://localhost:8080,那么它請求的地址即為 http://localhost:8080/api
這個 /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' 改成 '',也是可以的)
完