123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- import http from './interface'
- export const $http = (url, method, data, json, isAuth, isBuffer) => {
- let authorization = uni.getStorageSync('authorization') || 'Basic cmVucmVuaW86cmVucmVuaW8=';
- let access_token = uni.getStorageSync('access_token') || '';
- //设置请求前拦截器
- http.interceptor.request = (config) => {
- uni.showLoading({
- title: '加载中...'
- })
- config.header = {
- 'content-type': json ? 'application/json' : 'application/x-www-form-urlencoded',
- 'access_token': access_token
- }
- if (isAuth) config.header.authorization = authorization;
- if (isBuffer) config.responseType = 'arrayBuffer';
- }
- //设置请求结束后拦截器
- http.interceptor.response = async (response) => {
- //判断返回状态 执行相应操作
- uni.hideLoading()
- if ((response.data && response.data.code && response.data.code === 401) ||
- (response.data && response.data.msg && (response.data.msg.indexOf('未授权') > -1 ||
- response.data.msg.indexOf('重新登录') > -1))) {
- return uni.showModal({
- title: '温馨提示',
- content: '当前登录已失效,是否重新登录?',
- success: (res) => {
- if (res.confirm) {
- uni.clearStorageSync();
- uni.reLaunch({
- url: '/pages/login/index'
- })
- }
- }
- })
- }
- // 请根据后端规定的状态码判定
- if (response.data.code === 300) { //token失效
- // return response.data = await doRequest(response, url)//动态刷新token,并重新完成request请求
- } else {
- if (response.data.code == 10021 && response.data.msg) {
- uni.showToast({
- title: response.data.msg,
- icon: 'none',
- duration: 1500
- })
- }
- }
- return response;
- }
- return http.request({
- method: method,
- url: url,
- dataType: 'json',
- data,
- })
- }
- async function login() {
- return new Promise(resolve => {
- uni.login({
- provider: 'weixin',
- success(loginRes) {
- resolve(loginRes.code)
- },
- fail() {}
- });
- })
- }
- function postJson(url, data, json = true, isAuth = true, isBuffer = false) {
- return $http(url, 'POST', data, json, isAuth, isBuffer)
- }
- function get(url, data, json = true, isAuth = true, isBuffer = false) {
- return $http(url, 'GET', data, json, isAuth, isBuffer)
- }
- function post(url, data, json = true, isAuth = true, isBuffer = false) {
- return $http(url, 'POST', data, json, isAuth, isBuffer)
- }
- function put(url, data, json = true, isAuth = true, isBuffer = false) {
- return $http(url, 'PUT', data, json, isAuth, isBuffer)
- }
- function del(url, data, json = true, isAuth = true, isBuffer = false) {
- return $http(url, 'DELETE', data, json, isAuth, isBuffer)
- }
- export default {
- postJson,
- get,
- post,
- put,
- del
- }
|