微信小程序获取后端接口(使用develop,trial,release)调用不同开发环境

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.返回值查看

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值