1. 新建request.js文件,用来配置请求和响应
export default {
config: {
baseURL: 'https://www.holardata.com/ergj',
getToken() {
let token = uni.getStorageSync('userToken');
if (!token) {
return uni.switchTab({
url: '/pages/login/login'
})
}
return token
},
// 请求拦截器
beforeRequest(options = {}) {
return new Promise((resolve, reject) => {
options.url = this.baseURL + options.url;
options.method = options.method || 'GET';
options.header = {
"Authorization": "Bearer " + this.getToken()
}
resolve(options)
})
},
// 响应拦截器
handleResponse(data) {
return new Promise((resolve, reject) => {
const [err, res] = data;
if (res && res.statusCode !== 200) {
let msg = res.data.msg || '请求错误';
uni.showToast({
icon: 'none',
title: msg
})
return reject(msg)
}
if (err) {
uni.showToast({
icon: 'none',
title: '请求错误'
})
return reject(err)
}
return resolve(res.data)
})
},
},
request(options = {}) {
return this.config.beforeRequest(options).then(opt => {
return uni.request(opt)
}).then(res => this.config.handleResponse(res))
}
}
2.新建index.js,用来整合所有的接口
import api from './request'
// 水印图片
function getPhotoImg(data) {
return api.request({
method: 'post',
url: '/jcxywzx/add',
data: data
})
}
// 验证码
function getCode(data) {
return api.request({
method: 'get',
url: '/api/v1/login/checkCode',
responseType: 'arraybuffer',
data: data
})
}
// 登录
function getLogin(data) {
return api.request({
method: 'post',
url: '/api/v1/login/auth2',
data: data
})
}
// 告警列表
function getAlarm(data) {
return api.request({
method: 'get',
url: '/alarm/page',
data: data
})
}
export {
getPhotoImg,
getCode,
getLogin,
getAlarm
}
3.调用接口
import {
getAlarm
} from '../../api/index.js'
async getAlarmDataFun() {
const {
code,
data,
msg
} = await getAlarm();