uni-app 的請求接口在官方文檔里是這樣的
uni.request({ url: 'https://www.example.com/request', //僅為示例,並非真實接口地址。 data: { text: 'uni.request' }, header: { 'custom-header': 'hello' //自定義請求頭信息 }, success: (res) => { console.log(res.data); this.text = 'request success'; } });
在common 中 http.js文檔中進行如下封裝:
const baseUrl = '****'; //請求地址 const httpRequest = (opts, data) => { let httpDefaultOpts = { url: baseUrl+opts.url, data: data, beforeSend :function(xmlHttp){ xmlHttp.setRequestHeader("If-Modified-Since","0"); xmlHttp.setRequestHeader("Cache-Control","no-cache"); }, method: opts.method, header: opts.method == 'GET' ? { 'X-Requested-With': 'XMLHttpRequest', "Accept": "application/json", "Content-Type": "application/json; charset=UTF-8" } : { 'content-type': 'application/x-www-form-urlencoded' }, dataType: 'json', } let promise = new Promise(function(resolve, reject) { uni.request(httpDefaultOpts).then( (res) => { resolve(res[1]) } ).catch( (response) => { reject(response) } ) }) return promise }; export default { baseUrl, httpRequest }
在頁面中引入http.js
在需要接口請求的部分可以這樣寫:
http.httpRequest({ url: '/api/mineralInfo', //接口地址 method: 'POST' //請求方式 },{ submitStatus:1 //參數部分 }).then( res => { if(res.data.code == "0"){ //請求成功 } }, error => { console.log('網絡請求錯誤,請稍后重試!'); return; } );