在request 文件夹 新建request.js
import main from "main.js"
export const request = (options) => {
return new Promise((resolve, reject) => {
let token = uni.getStorageSync('token')
options.header.Authorization = token
uni.request({
url: main.baseUrl + options.url,
data: options.data || {},
method: options.method || 'POST',
header: options.header,
success: (res) => {
if (res.data.code == 401) {
if (uni.getStorageSync("userData") == null || uni.getStorageSync(
"userData") == "") {
uni.reLaunch({
url: '/pages/login/login'
})
} else {
uni.request({
url: main.baseUrl + '/user/login',
data: {
username:"123456",
password:"123456"
},
header: {
'content-type': 'application/x-www-form-urlencoded',
},
method: 'post',
success: (res) => {
if (res.data.code == 200) {
uni.setStorageSync("token", res.data.msg)
options.header.Authorization = uni
.getStorageSync('token')
uni.request({
url: main.baseUrl + options.url,
data: options.data || {},
method: options.method || 'POST',
header: options.header,
success: (res) => {
resolve(res.data)
}
})
}
}
})
}
} else {
resolve(res.data)
}
},
fail: (err) => {
uni.showToast({
title: "请检查网络连接",
icon: 'none',
duration: 1000
})
reject(err)
},
catch: (e) => {
console.log(e);
}
})
})
}
export default {
request
}

- 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
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
在main.js 下添加
export default {
baseUrl: "http://192.168.0.18:8081"
}
页面中引用
import request from "@/request/request.js"
绑定事件调用接口
getcodes() {
request.request({
url: '/getPhoneCode',
data: {
username: this.username
},
header: {
'content-type': 'application/x-www-form-urlencoded'
},
method: 'post',
}).then(res => {
console.log("------res------", res)
})
}