uniapp封装请求
request.js文件
import Vue from 'vue'
// 全局配置
import settings from './settings.js'
function computedBaseUrl(url) {// console.log(url);return (url.indexOf('http') === -1 ? settings.baseUrl : '') + url
}// 发送请求
export default (options) => {const {url = '',method = 'GET',data = {},header = {}} = optionsreturn new Promise((resolve, reject) => {try {if (options.headers.isToken == true) {uni.request({url: computedBaseUrl(url),method,data,header: {// "Content-Type": "multipart/form-data",// "Token": uni.getStorageSync('token'),"Authorization": uni.getStorageSync('token'),// "Authorization" : 'Bearer ' + JSON.parse(uni.getStorageSync('token')), // 让每个请求携带自定义token 请根据实际情况自行修改...header},success(e) {// console.log(e.data,'success');if (e.data.code == 401) {uni.reLaunch({url: '/pages/login/login',});}resolve(e.data)},fail(e) {// console.log(e,'fail');if (e && e.data && e.data.code == 401) {uni.reLaunch({url: '/pages/login/login',});}reject({...e,msg:e.errMsg||e.msg||'未知错误'})}})}else{uni.request({url: computedBaseUrl(url),method,data,header: {// "Content-Type": "multipart/form-data",// "Token": uni.getStorageSync('token'),// "Authorization": uni.getStorageSync('token'),// "Authorization" : 'Bearer ' + JSON.parse(uni.getStorageSync('token')), // 让每个请求携带自定义token 请根据实际情况自行修改...header},success(e) {if (e.data.code == 401) {uni.reLaunch({url: '/pages/login/index',});}resolve(e.data)},fail(e) {if (e.data.code == 401) {uni.reLaunch({url: '/pages/login/index',});}reject({...e,msg:e.errMsg||e.msg||'未知错误'})}})}} catch (err) {reject({...err,msg:err.errMsg||err.msg||'未知错误'})}}).then(data => data).catch(err => [err, null])
}
settings.js文件
export default {baseUrl:'http://127.0.0.1',uploadUrl:''
}
注意事项
setting中设置地址,方便进行统一管理,
settinngs.js和request.js文件是同级,放在一个文件夹中即可
使用方式
创建一个api文件夹
import request from "@/utils/request.js"// 接口模板
export function getLogin(data = {}) {return request({url: '/api/wx/wxLogin',method: 'post',data,headers: {isToken: false},})
}
注意小技巧
上面的headers中的isToken,方便对接口进行管理,因为微信小程序强制登录是不能通过审核的,所以有时候要后端放开接口,不需要token,也可哟访问,提高审核的通过率,这边就很方便管理!
结束语
欢迎指教