借鑒博客:https://blog.csdn.net/weixin_54882119/article/details/115979162
1、在項目下建一個api目錄,目錄里建一個api.js文件,內容如下:
const token = ''; const apiUrl = 'http://xxx/api/'; const baseRequest = (url, method, params) => { return new Promise((resolve, reject) => { uni.request({ url: apiUrl+url,//測試接口 method: method, data: params, header: { 'token': token } }).then((response)=>{ let [error, res] = response; resolve(res.data); }).catch(error => { //彈出消息提示 uni.showToast({ // icon: 'success', //最多顯示7個漢字長度 icon: 'none', //不顯示圖標,最多顯示2行 title: '服務器錯誤!', duration: 2000 }) let [err, res] = error; reject(err); }); }) }; export default{ baseRequest }
2、在main.js中配置vue全局屬性,以便調用api.js文件中的baseRequest方法,代碼:
import api from './api/api.js' Vue.prototype.$api = api
3、直接在要用到的組件頁面調用,調用代碼如下:
this.$api.baseRequest('loginController/login', 'POST', {}).then(res=>{ console.log("測試封裝請求api成功,返回結果:" + res.message); }).catch(error=>{ console.log(error); });
測試成功:
。