微信小程序向后端发送请求

wx.request

get请求

wx.request({
      url: url,//接口地址
      data: {},//请求参数  可以不写
      dataType: json,//返回的数据格式  可以不写
      header: {content-type:application/json},//设置请求的 header  可以不写
      method: GET,//HTTP 请求方法默认方法为GET
      responseType: text,//响应的数据类型
      success: (result) => {},//
      complete: (res) => {},//
      fail: (res) => {}//
    })

在request成功后可以通过打印数据查询到请求的数据

post请求

与get请求不同的是:

header需要改成 : "Content-Type": "application/x-www-form-urlencoded"

method处改成post

data中有些数据需要对格式进行转换,使用JSON.Stringify() 将json对象转换成json字符串格式

wx.request({
      url : "#",
      method: "POST",
      data: {
        stata : JSON.stringify(this.data.stata),
        _id:_id,
        mesg : this.data.mesg
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res);
      },
    })
经验分享 程序员 微信小程序 职场和发展