封装API接口
import {http} from '../utils/request.js'
export function login(code){return http({url:'/wx/getSession',method: 'GET',data:{code}})
}
调用接口
import {login,test,phoneMessage,updateAvatar} from '../../api/user.js'
function userLogin(){ login(code.value).then(r=>{toekn.value=r.data.tokenuni.setStorageSync('Authorization',toekn.value)})
}export function updateAvatar(uri){return uni.uploadFile({url:'/wx/uploadAvatar',filePath:uri,name:'file',headers: {'Content-Type': 'application/json; charset=UTF-8',},})
}
请求拦截器
const config={invoke(options){ if(!options.url.startsWith('http')){ options.url=baseUrl+options.url }options.timeout=1000*5 options.header = { ...options.header,};const token = uni.getStorageSync('Authorization'); if(token){options.header.Authorization=token }}
}uni.addInterceptor('request',config)
响应拦截器
const http = (options) => {return new Promise((resolve, reject) => {uni.request({...options,success(res) {resolve(res.data)},fail(err) {uni.showToast({icon: "none",title: "网络错误, 换个网络试试",});reject(err);},complete() {uni.hideLoading();},});});
};
文件上传
uni.addInterceptor("uploadFile", config);