uniapp对接口的封装(判断是否携带token)
先在跟目录下创建utils文件夹存放接口工具类,再在改文件夹下创建myRequest.js
// 异步请求接口封装
const baseUrl = 'http://localhost:1015';
// 不带token请求
export const httpRequest = (opts, data) => {
uni.onNetworkStatusChange(function(res) {
if (!res.isConnected) {
uni.showToast({
title: '网络连接不可用!',
icon: 'none'
});
}
return false
});
let httpDefaultOpts = {
url: baseUrl + opts.url,
data: data,
method: opts.method,
header: opts.method == 'get' ? {
'X-Requested-With': 'XMLHttpRequest',
"Accept": "application/json",
"Content-Type": "application/json; charset=UTF-8"
} : {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json; charset=UTF-8'
},
dataType: 'json',
}
let promise = new Promise(function(resolve, reject) {
uni.request(httpDefaultOpts).then(
(res) => {
resolve(res[1])
}
).catch(
(response) => {
reject(response)
}
)
})
return promise
};
//带Token请求
export const httpTokenRequest = (opts, data) => {
uni.onNetworkStatusChange(function(res) {
if (!res.isConnected) {
uni.showToast({
title: '网络连接不可用!',
icon: 'none'
});
}
return false
});
//此token是登录成功后后台返回保存在storage中的
let token = uni.getStorageSync('token');
// hadToken()
if (token == '' || token == undefined || token == null) {
uni.showToast({
title: '账号已过期,请重新登录',
icon: 'none',
complete: function() {
uni.reLaunch({
url: '/pages/login/index'
});
}
});
} else {
let httpDefaultOpts = {
url: baseUrl + opts.url,
data: data,
method: opts.method,
header: opts.method == 'get' ? {
'X-Access-Token': token,
'X-Requested-With': 'XMLHttpRequest',
"Accept": "application/json",
"Content-Type": "application/json; charset=UTF-8"
} : {
'X-Access-Token': token,
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json; charset=UTF-8'
},
dataType: 'json',
}
let promise = new Promise(function(resolve, reject) {
uni.request(httpDefaultOpts).then(
(res) => {
if (res[1].data.code == 200) {
resolve(res[1])
} else {
if (res[1].data.code == 5000) {
// uni.showModal({
// title: '提示',
// content: res[1].data.message,
// success: function (res) {
// if (res.confirm) {
// uni.reLaunch({
// url: '/pages/login/login'
// });
// uni.clearStorageSync();
// }
// }
// });
uni.reLaunch({
url: '/pages/login/index'
});
uni.clearStorageSync();
} else {
resolve(res[1])
// uni.showToast({
// title: '' + res[1].data.message,
// icon: 'none'
// })
}
}
}
).catch(
(response) => {
reject(response)
}
)
})
return promise
}
};
export const hadToken = () => {
let token = uni.getStorageSync('token');
if (token == '' || token == undefined || token == null) {
uni.showToast({
title: '账号已过期,请重新登录',
icon: 'none',
complete: function() {
uni.reLaunch({
url: '/pages/login/index'
});
}
});
return false;
}
return true
}
export default {
baseUrl,
httpRequest,
httpTokenRequest,
hadToken
}
写好myRequest.js封装的接口文件夹后,我们要全局注册这个封装类
在main.js中注入
import Vue from 'vue'
import App from './App'
// 此处导入自定义的封装网络请求(加token)
// 不带token请求
import {httpRequest} from './utils/myRequest.js'
// 挂载到全局,让所有的页面都能调用httpRequest方法
Vue.prototype.$httpRequest = httpRequest
// 带Token请求
import {httpTokenRequest} from './utils/myRequest.js'
// 挂载到全局,让所有的页面都能调用httpTokenRequest方法
Vue.prototype.$httpTokenRequest = httpTokenRequest
// hadToken
import {hadToken} from './utils/myRequest.js'
// 挂载到全局,让所有的页面都能调用hadToken方法
Vue.prototype.$hadToken = hadToken
// 导入全局变量 baseUrl
import baseUrl from './utils/myRequest.js'
// 挂载到全局,让所有的页面都能调用baseUrl方法
Vue.prototype.$baseUrl = baseUrl
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
这时你就已经可以全局应用他了
<template>
</template>
<script>
export default {
data() {
},
methods: {
myMethods(){
let opts = {
url: '/pcuser/login',
method: 'POST',
};
let data = loginParams;
this.$httpTokenRequest(opts, data).then((res) => {
console.log(res)
this.loading = false;
if (res.data.code === 20000) { // 获取数据成功
console.log("成功")
uni.switchTab({
url: '../index/index'
})
this.$tip.success('登录成功!')
} else if (res.data.code === 500) { // 获取数据失败
console.log("失败")
this.loading = false;
this.$tip.alert(res.data.message);
}
}).catch((err) => {
let msg = "请求出现错误,请稍后再试"
this.loading = false;
this.$tip.alert(msg);
}).finally(() => {
this.loading = false;
})
}
}
}
</script>