1.在app.js中创建微信小程序的不同环境
const URLMap= {
develop:'https://..........', //测试服
trial:'https://..........', //体验服
release:'https://..........', //正式服
}
App({
property:{
host:"",
},
onLaunch(){
//wx.getAccountInfoSync获取对应的开发环境
const accountInfo = wx.getAccountInfoSync();
const nowEnv = accountInfo.miniProgram.envVersion;
this.property.host = URLMap[nowEnv];
}
})
2.在api里新建request.js
// 使用promise 封装http请求避免回调地狱
const GET = 'get';
const POST = 'post';
//接入app.js使用的不同环境的变量
const app = getApp();
//app.property.host // 接口请求地址
module.exports = function (options) {
return new Promise(function(resolve, reject) {
let header = {
'content-type': 'application/json'
};
wx.request({
url: app.property.host + options.url,
method: options.method,
data: options.method === POST ? JSON.stringify(options.data) : options.data,
header: header,
success(res) {
// 请求到接口前页面展示loading
wx.showLoading({
title: '加载中...',
success: function() {
// 请求成功
// 判断状态码,根据后端定义来判断
// if (res.data.code == 600) {
// resolve(res);
// } else {
// // 其他异常
// reject(res);
// wx.showToast({
// title: res.data.msg,
// icon: 'none'
// })
// }
resolve(res.data)
}
})
},
fail: function (err) {
// 请求失败
reject(err)
wx.showToast({
title: '网络繁忙,请稍后重试~',
icon: 'none'
})
},
complete: function () {
// 配对使用(loading消失)
wx.hideLoading();
}
})
})
}
3.新增userApi接口文档
const request = require('./request')
//样式一
export function gettime(data){
return request({
url:'/account/getTime',
method:'post',
data
})
}
//样式二
export function gettime(){
return request({
url:'/account/getTime',
method:'post',
})
}
//样式三
export function gettime(data){
return request({
url:'/account/getTime',
method:'get',
data
})
}
4.调用接口
const {gettime} =require('../../api/userApi');
gettime().then(res=>(console.log(res)))
5.返回值查看