如果你做過Angular或者Vue的話忘朝,你會發(fā)現(xiàn),微信小程序跟他們有很多相似的地方判帮,相比來說局嘁,小程序要簡單一些。http請求的封裝也是一樣晦墙,廢話不多說 悦昵,直接上步驟。
1晌畅、創(chuàng)建一個http.js,代碼如下:
let rootUrl = "http://www.baidu.com";//具體接口域名根據(jù)你的實際情況填寫
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里配置全局函數(shù)
var http = require('http/http.js') //引入剛創(chuàng)建的http.js,地址根據(jù)自己的地址填寫
App({
onLaunch: function() {
//調用API從本地緩存中獲取數(shù)據(jù)
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"
},
//事件處理函數(shù)
changeMenus: function(){
let postdata = {
userId:12
}
app.func.req('/abner/web/getUserByOpenId',postdata,(res)=>{
console.log(res)
}
})
}
})