uniapp 封装请求接口 (带token)
1.在创建好的uniapp项目中新建文件夹util,再新建config.js文件配置baseUrl
export default {
baseUrl : 'https://xxxx.com'
}
2.新建request.js文件 ,封装请求
import config from "./config.js"
const headers = {}
const url = {}
url.request = async (url, params = {}, method, needDataSource = 0, needToken = false, needLoading = true) => {
if (needLoading == true) {
uni.showLoading({
title: '加载中',
})
}
if (needToken) {
const Authorization = uni.getStorageSync('token')
headers['Authorization'] = 'Bearer '+Authorization
}else {
delete headers['Authorization'];
}
switch (needDataSource) {
case 0:
headers['x-datasource'] = 'shtraining'
break;
case 1:
headers['x-datasource'] = 'shtraining-lab'
break;
}
let full_url = config.baseUrl + url;
return await uni.request({
url: full_url,
header: headers,
data: params||{},
method: method,
}).then(res => {
uni.hideLoading()
if (!res) {
return 0;
}
console.log(res.data);
return res.data;
}).catch(parmas => {
uni.hideLoading()
switch (parmas.code) {
case 401:
uni.clearStorageSync()
break
default:
uni.showToast({
title: parmas.message,
icon: 'none'
})
return Promise.reject()
break
}
})
}
export default url
3.在util中新建publicapi.js文件
public_api.getUserInfo = params => url.request('/api/usercenter/userDetails',params,'GET',0,true)
public_api.getLabel = params => url.request('/api/show/getLabel', params, 'POST',1)
public_api.getContent = params => url.request('/api/getContentByChannelId',params,'GET',1)
...
4.在main.js中修改
import Vue from 'vue'
import request from './util/request.js'
import api from "./util/publicapi.js"
Vue.prototype.$api = api
5.页面中使用
this.$api.getUserInfo({}).then(res=>{
console.log(res,'用户信息')
if(res.code ==0){
let data = res.data
this.userInfo = {
id:data.id,
uname: data.username,
avatar:data.identificationPhotoDefault
}
uni.setStorageSync('userInfo',data)
}
})