一、创建config.js(判断开发环境)
if (process.env.NODE_ENV === 'development') {
// 开发环境
url_config = 'http://'
} else {
// 生产环境
url_config = 'http://'
}
export default url_config
二、创建request.js
import urlConfig from './config.js'
import { getToken } from '@/utils/auth.js'
const request = {}
const headers = {}
request.globalRequest = (url, method, data) => {
if (!data) {
data = {}
}
if (getToken()) {
headers['Authorization'] = 'Bearer ' + getToken() || ''
}
console.log(data);
return new Promise((resolve, reject) => {
uni.request({
url: urlConfig + url,
method: method,
data: data,
sslVerify: false,
dataType: 'json',
header: headers,
timeout: 5 * 1000
}).then(res => {
console.log("当前接口调用==: " + urlConfig + url);
const new_data = res[1].data
console.log(new_data)
if (new_data.code && new_data.code == 200) {
resolve(new_data)
} else {
uni.showToast({
title: new_data.msg,
icon: 'none',
duration: 3 * 1000
})
reject(new_data.msg || '请求失败,请重新尝试')
}
}).catch(res => {
uni.showModal({
title: '提示',
content: '请求失败,请重新尝试',
showCancel: false
})
reject(res.msg || '请求失败,请重新尝试')
})
})
}
export default request
auth.js
const TokenKey = ''
export function getToken () {
return uni.getStorageSync(TokenKey)
}
export function setToken (accessToken) {
uni.setStorage({
key: TokenKey,
data: accessToken
})
}
export function removeToken () {
uni.clearStorageSync()
}
三、封装接口api
/*
* login.js
*/
import request from '@/utils/request.js'
export function login(params) {
return request.globalRequest(`/login`, 'POST', params)
}
四、调用
import { login } from '@/api/login.js'
login(params).then(res => {
// 成功
}).catch(error => {
// 失败
})