一、在根目录下创建文件夹utils,在该目录下创建文件api.js及http.js
二、在http.js中封装,如需验证token/sign或者其他字段信息,可添加方法进行验证再进行回调
let token = '';//token
let sign = '';//签名
let data = {
token,
sign
};
function http(url, method, params) {
// data:表示请求要发送的数据,success:成功的回调,fail:失败的回调,这三个字段可缺可无,其余字段会忽略
if (params.data) {
for (let key in params.data) { // 在这里判断传过来的参数值为null,就删除这个属性
if (params.data[key] == null || params.data[key] == 'null') {
delete params.data[key]
}
}
data = {
...data,
...params.data
}
}
uni.request({
url:url,
method: method == 'post' ? 'post' : 'get',
data,
header: {
'content-type': method == 'get' ? 'application/json' : 'application/x-www-form-urlencoded'
},
success(res) {
params.success && params.success(res.data)
},
fail(err) {
uni.showToast({
title: '服务器请求失败',
icon: 'none',
duration: 1500
})
params.fail && params.fail(err)
},
complete() {
setTimeout(() => {
uni.hideLoading();
},1500)
}
})
}
module.exports = {
http
}
三、api.js
import { http } from './http';//引进封装方法
/*
接口
*/
const Url = 'http://******.cn/';//域名
//首页接口
const index = {
dream:"***/list"
};
// 方法
function getDream(params){
http(Url + index.dream, 'get', params)
}
// 暴露方法
export default {
getDream
}
四、页面调用
import api from '../../utils/api';//引进
//调用方式
api.userLogin({
data:{
key:'***',
text:'测试',
type:'1'
},
//成功回调
success:res =>{
console.log(res)
}
})
借鉴于:https://www.cnblogs.com/lhl66/p/12888408.html,如果侵权请联系删除