微信小程序使用HTTP请求_绕过HTTPS_云函数 request-promise get、post
发布于 4 年前 作者 likong 2754 次浏览 来自 分享

request-promise GET 请求

1、云函数中

> `云函数的console.log();只能在云函数的日志中查看,不会打印到控制台上,以为云函数不是本地`

// 云函数入口文件
const cloud = require('wx-server-sdk')
//引入request-promise用于做网络请求
var rp = require('request-promise');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
// 云函数入口函数
exports.main = async (event, context) => {
  let url = event.url;
  // console.log('前端参数');
  // console.log(event);
  if(url == null || url == undefined ){
    return 'URL不存在'
  }else{
    return await rp(url)
    .then(function (res) {
      return res
    })
    .catch(function (err) {
      return '请求失败'
    });
  }
}

 

小程序js中

wx.showLoading({
      title: '加载中',
      mask: true
    });
    var that = this;
    wx.cloud.callFunction({
      name: 'HttpGetNotepad',//你的云函数名称
      data: {
      //对于get请求我们的参数可以直接拼接在url?后面,多个参数使用 & 了解 如:url?a=1&b=1 我这里是使用 RESTful 风格的URL
        url: 'http://ip或者域名:端口/notepad/'+app.globalData.openid
      }
    }).then( (res)=>{
      // console.log(res);
      var result = JSON.parse(res.result);
      if(result.code == 200){
        that.setData({
          noepadInfo: result.data
        })
      }else{
        wx.showToast({
          title: '服务器错误',
          duration: 2000
        });
        // wx.hideLoading();
      }
      wx.hideLoading();

    }).catch( (res)=>{
      // console.log(res);
      wx.showToast({
        title: '服务器断开',
        duration: 2000
      });
      wx.hideLoading();
    })

springboot后端

 [@GetMapping](/user/GetMapping)("/notepad/{opendId}")
    public Result getUserContent([@PathVariable](/user/PathVariable)("opendId") String opendId){
        List<User_Notepad> notepadByOpendId = user_service.findNotepadByOpendId(opendId);
        return Result.success(notepadByOpendId);
    }

request-promise POST 请求

这一部分是个重点,有两种传递参数的方式

1、 使用form表单传递参数

云函数

// 云函数入口文件
const cloud = require('wx-server-sdk')
//引入request-promise用于做网络请求
var rp = require('request-promise');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
// 云函数入口函数
exports.main = async (event, context) => {
  // console.log(event);
  let url = event.url;
  if(url == null || url == undefined ){
    return 'URL不存在'
  }else{
    return await rp({
      url: url,
      method: "POST",
      json: true,
      form: {
        openId: event.openId,
        content: event.content,
        date: event.date,
        startAddress: event.startAddress,
        startPoint: event.startPoint,
        endAddress: event.endAddress,
        endPoint: event.endPoint,
        startTime: event.startTime,
        endTime: event.endTime,
        beforTime: event.beforTime,
        remind: event.remind
      },
      headers: {
        //"content-type": "application/json",
        "content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
      },
    })
    .then(function (res) {
      return res
    })
    .catch(function (err) {
      return '请求失败'
    });
  }

}

小程序js调用

//发送请求到服务器
	//这只是为了用户友好性做的显示 loading 
      wx.showLoading({
        title: '保存中',
        mask: true
      })
  
      wx.cloud.callFunction({
        name: 'HttpAddNotepad',//你的云函数名称
        data: {
          // url: 'http://lw.free.idcfengye.com/notepad',
          url: 'http://ip或者域名/notepad',
          openId: app.globalData.openid,
          content: this.data.zhuti,
          date: this.data.date,
          startAddress: this.data.startAddress,
          startPoint: this.data.startPoint,
          endAddress: this.data.endAddress,
          endPoint: this.data.endPoint,
          startTime: this.data.timeStart,
          endTime: this.data.timeEnd,
          beforTime: this.data.tiqian,
          remind: (this.data.flag?1:0)
        }
      }).then( (res)=>{
        // console.log(res);
        if(res.result.code == 200 || res.result.data >0){
          wx.showToast({
            title: '保存成功',
            duration: 1000
          });
          //返回页面
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })
          }, 1000)
        }else{
          wx.showToast({
            title: '保存失败',
            duration: 2000
          });
          // wx.hideLoading();
        }
      }).catch( (res)=> {
        // console.log(res);
        wx.showToast({
          title: '保存失败',
          duration: 2000
        });
        // wx.hideLoading();
      })

springboot后端

	 [@PostMapping](/user/PostMapping)("/notepad")
	 //这里不能使用 [@RequestBody](/user/RequestBody) 接收数据,只能是自动入参
    public Result addUserNotepad( User_Notepad notepad ) throws Exception{
        JobAndTrigger jt = null;
        
        if(notepad.getRemind() == 1 && notepad.getBeforTime()!=null && notepad.getStartTime()!=null){
           
            jt = user_service.addSendJob(notepad);
        }
        //数据入库
        notepad.setJt(jt);

        int row = user_service.insertUseNotepad(notepad);
        return Result.success("添加成功",notepad.getId());
    }

2、使用body传递参数

云函数

// 云函数入口文件
const cloud = require('wx-server-sdk')
//引入request-promise用于做网络请求
var rp = require('request-promise');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  let url = event.url;
  let data = event.info;
  // console.log(data);

  if(url == null || url == undefined ){
    return 'URL不存在'
  }else{
    return await rp({
      url: url,
      method: "POST",
      json: true,
      body: data,//这里就是使用的json格式的数据
      headers: {
        "content-Type": "application/json",
        // "content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        // 'User-Agent': 'Request-Promise'
        // "token": event.token
      },
    })
    .then(function (res) {
      return res
    })
    .catch(function (err) {
      return '请求失败'
    });
  }
}

小程序js调用

	//构造数据 数据可以在 调用云函数的data中写,这里是个人风格这么写,没有强制要求
      var info = 
      {
        id: this.data.notepadInfo.id,
        openId: app.globalData.openid,
        content: this.data.zhuti,
        date: this.data.date,
        startAddress: this.data.startAddress == this.data.notepadInfo.startAddress?null:this.data.startAddress,
        startPoint: this.data.startPoint == this.data.notepadInfo.startPoint?null:this.data.startPoint,
        endAddress: this.data.endAddress == this.data.notepadInfo.endAddress?null:this.data.endAddress,
        endPoint: this.data.endPoint == this.data.notepadInfo.endPoint?null:this.data.endPoint,
        startTime: this.data.timeStart,
        endTime: this.data.timeEnd,
        beforTime: this.data.tiqian,
        remind: (this.data.flag?1:0),
      }
      // console.log(info);
      wx.cloud.callFunction({
        name: 'HttpUpdateRemind',
        data: {
          url: 'http://ip或者域名/upnotepad',
          info: info //json格式的数据
        }
      }).then( (res)=>{
        // console.log(res);
        if(res.result.code == 200 || res.result.data >0){
          wx.showToast({
            title: '修改成功',
            duration: 1000
          });
          //返回页面
          setTimeout(function () {
            wx.redirectTo({
              url: '/pages/myNotepad/myNotepad'
            })
          }, 1000)
        }else{
          wx.showToast({
            title: '修改失败',
            duration: 2000
          });
          // wx.hideLoading();
        }
      }).catch( (res)=> {
        // console.log(res);
        wx.showToast({
          title: '修改失败',
          duration: 2000
        });
        // wx.hideLoading();
      })

sprongboot后端

[@PostMapping](/user/PostMapping)("/remind/{flag}")
//这里就用 [@RequestBody](/user/RequestBody)接收参数
    public Result updateRemind([@PathVariable](/user/PathVariable)("flag") boolean flag, [@RequestBody](/user/RequestBody) User_Notepad notepad ) throws Exception{

        JobAndTrigger jt = null;
       
        if(notepad!=null && flag){
         
            jt = user_service.addSendJob(notepad);
            notepad.setJt(jt);
//            System.out.println(jt);
            notepad.setRemind(1);
        }else if(notepad!=null && !flag && notepad.getJt()!=null && (!StringUtils.isEmpty(notepad.getJt().getJobName())) ){
            jt = quartzService.deleteJob(notepad.getJt());
            notepad.setJt(jt);
//            System.out.println(jt);
            notepad.setRemind(0);
        }
        //数据入库
        int res = user_service.updateRemind(notepad);

        return Result.success("修改成功",notepad);
    }
回到顶部