12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- import Storage from './../store/storage.js';
- const ENV = require('./../.env.js')
- const HttpCodes = {
- UNAUTHORIZED: 401, //登录失效
- }
- class request {
- static request(method, url, data = null, that = null) {
- let promise = new Promise(function(resolve, reject) {
- let _url
- if (process.env.NODE_ENV !== 'production') {
- _url = ENV.APP_DEV_URL + url
- } else {
- _url = ENV.APP_PROD_URL + url
- }
- const param = {
- url: _url,
- method: method,
- data: data,
- header: {
- 'Authorization': 'Bearer ' + Storage.getToken(),
- 'Content-Type': 'application/json',
- },
- success(res) {
- if (res.statusCode === 200) {
- if (res.data.code === 200) {
- resolve(res.data)
- } else if (res.data.code == 401) {
- uni.reLaunch({
- url: '/pages/login'
- })
- } else if (res.data.code == 6401) {
- uni.request({
- url: ENV.APP_PROD_URL + '/api/refresh_token',
- method: 'GET',
- header: {
- 'Authorization': 'Bearer ' + Storage.getToken(),
- 'Content-Type': 'application/json',
- },
- }).then(res => {
- if (res.data.code == 200) {
- Storage.setToken(res.data.token)
- param.header.Authorization = 'Bearer ' + res.data.token
- uni.request(param)
- } else if (res.data.code == 401) {
- Storage.removeToken()
- Storage.removeCache('userInfo')
- uni.redirectTo({
- url: '/pages/login'
- })
- }
- })
- } else {
- resolve(res.data)
- }
- } else {
- resolve(res)
- }
- },
- fail(res) {
- resolve(res)
- }
- }
- uni.request(param)
- }).catch((res) => {
- if (res.statusCode === 200) {
- if (res.data.code !== 200) {
- return res.data
- }
- } else {
- console.log('服务器错误:', res)
- return res;
- }
- })
- return promise
- }
- static get(url, data, that) {
- return this.request('GET', url, data, that)
- }
- static post(url, data, that) {
- return this.request('POST', url, data, that)
- }
- static put(url, data, that) {
- return this.request('PUT', url, data, that)
- }
- static delete(url, data, that) {
- return this.request('DELETE', url, data, that)
- }
- }
- export default request
|