Blame view

utils/request.js 1.87 KB
290144e9   易尊强   第一次
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  import store from '@/store'
  import define from './define'
  const host = define.baseURL
  const defaultOpt = {
  	load: true
  }
  
  // 示例
  // async xxxx(code) {
  //   var res = await this.request({
  // 		url: '/api/System/DictionaryData/All',
  // 		method: 'GET',
  // 		data,
  // 		options: {
  // 			load: false
  // 		}
  // 	})
  //   if (!res) return
  //   console.log(res)
  // }
  
  function request(config) {
  	config.options = Object.assign(defaultOpt, config.options)
  	const token = uni.getStorageSync('token') || ''
  	let header = {
  		"Content-Type": "application/json;charset=UTF-8/x-www-form-urlencoded",
  		...config.header
  	}
  	if (token) header['Authorization'] = token
  	let url = config.url.indexOf('http') > -1 ? config.url : host + config.url
  	if (config.url === '/api/oauth/Login') {
  		url += '?client_id=admin&client_secret=123456&scope=all&grant_type=password'
  	}
  
6c679290   易尊强   3/6a上午
35
36
37
38
39
  	// if (config.options.load) {
  	// 	uni.showLoading({
  	// 		title: config.options.loadText || ''
  	// 	})
  	// }
290144e9   易尊强   第一次
40
41
42
43
44
45
46
47
48
  
  	return new Promise((resolve, reject) => {
  		uni.request({
  			url: url,
  			data: config.data || null,
  			method: config.method || 'GET',
  			header: header,
  			timeout: define.timeout,
  			success: res => {
6c679290   易尊强   3/6a上午
49
  				// uni.hideLoading()
290144e9   易尊强   第一次
50
51
52
53
  				if (res.statusCode === 200) {
  					if (res.data.code == 200) {
  						resolve(res.data)
  					} 
6c679290   易尊强   3/6a上午
54
55
56
57
  					else {
  						ajaxError(res.data)
  						reject(res.data.msg)
  					}
290144e9   易尊强   第一次
58
  				} 
6c679290   易尊强   3/6a上午
59
60
61
62
  				else {
  					ajaxError(res.data)
  					reject(res.errMsg)
  				}
290144e9   易尊强   第一次
63
64
65
66
67
68
69
70
71
  			},
  			fail: err => {
  				uni.hideLoading()
  				reject(err)
  			}
  		})
  	})
  }
  
6c679290   易尊强   3/6a上午
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
  function ajaxError(data) {
  	uni.showToast({
  		// title: data.msg || '请求出错,请重试',
  		// icon: 'none',
  		complete() {
  			if (data.code === 600 || data.code === 601 || data.code === 602) {
  				setTimeout(() => {
  					store.dispatch('user/resetToken').then(() => {
  						uni.reLaunch({
  							url: '/pages/login/index'
  						})
  					})
  				}, 1500)
  			}
  		}
  	})
  }
290144e9   易尊强   第一次
89
90
  
  export default request