微信小程序请求头header_微信小程序请求封装(http请求详解)

如果你做过Angular或者Vue的话,你会发现,微信小程序跟他们有很多相似的地方,相比来说,小程序要简单一些。http请求的封装也是一样,废话不多说 ,直接上步骤。

1、创建一个http.js,代码如下:

let rootUrl = "http://www.baidu.com";//具体接口域名根据你的实际情况填写

function getData(url,data,cb){

wx.request({

url : rootUrl + url,

data: data,

method: 'post',

header: {

// "Content-Type": "json", //get请求时候

"Content-Type": "application/x-www-form-urlencoded" //POST请求的时候这样写

},

success: function(res){

return typeof cb == "function" && cb(res.data)

},

fail: function(){

return typeof cb == "function" && cb(false)

}

})

}

module.exports = {

req : getData //暴露一个方法

}

这段代码有个坑:就是那个请求头header,如果是get请求

header{

"Content-Type": "json"

}

如果是post请求

header{

"Content-Type": "application/x-www-form-urlencoded" //POST请求的时候这样写

}

2、在小程序app.js里配置全局函数

var http = require('http/http.js') //引入刚创建的http.js,地址根据自己的地址填写

App({

onLaunch: function() {

//调用API从本地缓存中获取数据

var logs = wx.getStorageSync('logs') || []

logs.unshift(Date.now())

wx.setStorageSync('logs', logs)

},

getUserInfo: function(cb) {

var that = this

if (this.globalData.userInfo) {

typeof cb == "function" && cb(this.globalData.userInfo)

} else {

//调用登录接口

wx.getUserInfo({

withCredentials: false,

success: function(res) {

that.globalData.userInfo = res.userInfo

typeof cb == "function" && cb(that.globalData.userInfo)

}

})

}

},

globalData: {

userInfo: null

},

func:{

req:http.req //这里配置我们需要的方法

}

})

3、在项目代码中调用方法

var app = getApp() ;

Page({

data: {

title:"111111"

},

//事件处理函数

changeMenus: function(){

let postdata = {

userId:12

}

app.func.req('/abner/web/getUserByOpenId',postdata,(res)=>{

console.log(res)

}

})

}

})

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值