You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
100 lines
2.0 KiB
JavaScript
100 lines
2.0 KiB
JavaScript
/**
|
|
* 通用uni-app网络请求
|
|
* 基于 Promise 对象实现更简单的 request 使用方式,支持请求和响应拦截
|
|
*/
|
|
import config from "./config.js"
|
|
|
|
function request(options,contentType = 'normal') {
|
|
|
|
options.url = config.baseUrl + options.url
|
|
options.header = {
|
|
'Content-Type': contentType == 'json' ? 'application/json;charset=UTF-8' : 'application/x-www-form-urlencoded',
|
|
'Authorization': 'Bearer ' + uni.getStorageSync('userToken') || '',
|
|
}
|
|
|
|
return new Promise((resolve, reject) => {
|
|
let _config = null
|
|
|
|
options.complete = (response) => {
|
|
let statusCode = response.statusCode;
|
|
|
|
|
|
// 测试环境打印:统一的响应日志记录
|
|
_reslog(response)
|
|
|
|
if (statusCode === 200) { //成功,返回服务器返回数据
|
|
let data = response.data
|
|
if(data.code == 200){
|
|
resolve(data.data);
|
|
}
|
|
} else {
|
|
reject(response)
|
|
}
|
|
}
|
|
|
|
_config = Object.assign({}, config, options)
|
|
|
|
// 测试环境打印:统一的请求日志记录
|
|
_reqlog(_config)
|
|
|
|
uni.request(_config);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 请求接口日志记录
|
|
*/
|
|
function _reqlog(req) {
|
|
if (process.env.NODE_ENV === 'development') {
|
|
console.log("地址:" + req.url)
|
|
console.log("请求参数:" + JSON.stringify(req.data))
|
|
}
|
|
|
|
//TODO 调接口异步写入日志数据库
|
|
}
|
|
|
|
/**
|
|
* 响应接口日志记录
|
|
*/
|
|
function _reslog(res) {
|
|
if (process.env.NODE_ENV === 'development') {
|
|
console.log("响应结果:" + JSON.stringify(res.data))
|
|
}
|
|
}
|
|
|
|
|
|
export default {
|
|
get(url, data = null, contentType = 'normal') {
|
|
let options = {
|
|
url,
|
|
data,
|
|
method: 'GET'
|
|
}
|
|
return request(options, contentType)
|
|
},
|
|
post(url, data = null, contentType = 'normal') {
|
|
let options = {
|
|
url,
|
|
data,
|
|
method: 'POST'
|
|
}
|
|
return request(options, contentType)
|
|
},
|
|
put(url, data = null, contentType = 'normal') {
|
|
let options = {
|
|
url,
|
|
data,
|
|
method: 'PUT'
|
|
}
|
|
return request(options, contentType)
|
|
},
|
|
delete(url, data = null, contentType = 'normal') {
|
|
let options = {
|
|
url,
|
|
data,
|
|
method: 'DELETE'
|
|
}
|
|
return request(options, contentType)
|
|
}
|
|
}
|