這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)如何在微信小程序中封裝網(wǎng)絡(luò)請(qǐng)求,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
創(chuàng)新互聯(lián)建站專注于桂林網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠為您提供桂林營銷型網(wǎng)站建設(shè),桂林網(wǎng)站制作、桂林網(wǎng)頁設(shè)計(jì)、桂林網(wǎng)站官網(wǎng)定制、微信平臺(tái)小程序開發(fā)服務(wù),打造桂林網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供桂林網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。
網(wǎng)絡(luò)請(qǐng)求
網(wǎng)絡(luò)請(qǐng)求小程序提供了wx.request, 仔細(xì)看一下 api,這不就是n年前的 $.ajax 嗎,好古老啊。
// 官方例子
wx.request({
url: 'test.php', //僅為示例,并非真實(shí)的接口地址
data: {
x: '' ,
y: ''
},
header: {
'content-type': 'application/json' // 默認(rèn)值
},
success: function(res) {
console.log(res.data)
}
})小程序支持ES6,那么就應(yīng)該支持Promise 了,很開心~, 話不多說直接上代碼吧
Promise封裝
const baseUrl = 'https://api.it120.cc';
const http = ({ url = '', param = {}, ...other } = {}) => {
wx.showLoading({
title: '請(qǐng)求中,請(qǐng)耐心等待..'
});
let timeStart = Date.now();
return new Promise((resolve, reject) => {
wx.request({
url: getUrl(url),
data: param,
header: {
'content-type': 'application/json' // 默認(rèn)值 ,另一種是 "content-type": "application/x-www-form-urlencoded"
},
...other,
complete: (res) => {
wx.hideLoading();
console.log(`耗時(shí)${Date.now() - timeStart}`);
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(res.data)
} else {
reject(res)
}
}
})
})
}
const getUrl = (url) => {
if (url.indexOf('://') == -1) {
url = baseUrl + url;
}
return url
}
// get方法
const _get = (url, param = {}) => {
return http({
url,
param
})
}
const _post = (url, param = {}) => {
return http({
url,
param,
method: 'post'
})
}
const _put = (url, param = {}) => {
return http({
url,
param,
method: 'put'
})
}
const _delete = (url, param = {}) => {
return http({
url,
param,
method: 'put'
})
}
module.exports = {
baseUrl,
_get,
_post,
_put,
_delete
}使用
const api = require('../../utils/api.js')
// 單個(gè)請(qǐng)求
api.get('list').then(res => {
console.log(res)
}).catch(e => {
console.log(e)
})
// 一個(gè)頁面多個(gè)請(qǐng)求
Promise.all([
api.get('list'),
api.get(`detail/${id}`)
]).then(result => {
console.log(result)
}).catch(e => {
console.log(e)
})登陸問題
做一個(gè)應(yīng)用,肯定避免不了登錄操作。用戶的個(gè)人信息啊,相關(guān)的收藏列表等功能都需要用戶登錄之后才能操作。一般我們使用token做標(biāo)識(shí)。
小程序并沒有登錄界面,使用的是 wx.login 。 wx.login 會(huì)獲取到一個(gè) code,拿著該 code 去請(qǐng)求我們的后臺(tái)會(huì)最后返回一個(gè)token到小程序這邊,保存這個(gè)值為 token 每次請(qǐng)求的時(shí)候帶上這個(gè)值。
一般還需要把用戶的信息帶上比如用戶微信昵稱,微信頭像等,這時(shí)候就需要使用 wx.getUserInfo ,這里涉及到一個(gè)用戶授權(quán)的問題
帶上用戶信息就夠了嘛? too young too simple!我們的項(xiàng)目不可能只有小程序,相應(yīng)的微信公眾平臺(tái)可能還有相應(yīng)的App,我們需要把賬號(hào)系統(tǒng)打通,讓用戶在我們的項(xiàng)目中的賬戶是同一個(gè)。這就需要用到微信開放平臺(tái)提供的 UnionID 。
登陸
//app.js
App({
onLaunch: function () {
console.log('App onLaunch');
var that = this;
// 獲取商城名稱
wx.request({
url: 'https://api.it120.cc/'+ that.globalData.subDomain +'/config/get-value',
data: {
key: 'mallName'
},
success: function(res) {
wx.setStorageSync('mallName', res.data.data.value);
}
})
this.login();
this.getUserInfo();
},
login : function () {
var that = this;
var token = that.globalData.token;
// 如果有token
if (token) {
// 檢查token是否有效
wx.request({
url: 'https://api.it120.cc/' + that.globalData.subDomain + '/user/check-token',
data: {
token: token
},
success: function (res) {
// 如果token失效了
if (res.data.code != 0) {
that.globalData.token = null;
that.login(); // 重新登陸
}
}
})
return;
}
// 【1】調(diào)用微信自帶登陸
wx.login({
success: function (res) {
// 【2】 拿到code去訪問我們的后臺(tái)換取其他信息
wx.request({
url: 'https://api.it120.cc/'+ that.globalData.subDomain +'/user/wxapp/login',
data: {
code: res.code
},
success: function(res) {
// 如果說這個(gè)code失效的
if (res.data.code == 10000) {
// 去注冊(cè)
that.registerUser();
return;
}
// 如果返回失敗了
if (res.data.code != 0) {
// 登錄錯(cuò)誤
wx.hideLoading();
// 提示無法登陸
wx.showModal({
title: '提示',
content: '無法登錄,請(qǐng)重試',
showCancel:false
})
return;
}
// 【3】 如果成功后設(shè)置token到本地
that.globalData.token = res.data.data.token;
// 保存用戶信息
wx.setStorage({
key: 'token',
data: res.data.data.token
})
}
})
}
})
},
// 注冊(cè)?? [這個(gè)看需求]
registerUser: function () {
var that = this;
wx.login({
success: function (res) {
var code = res.code; // 微信登錄接口返回的 code 參數(shù),下面注冊(cè)接口需要用到
wx.getUserInfo({
success: function (res) {
var iv = res.iv;
var encryptedData = res.encryptedData;
// 下面開始調(diào)用注冊(cè)接口
wx.request({
url: 'https://api.it120.cc/' + that.globalData.subDomain +'/user/wxapp/register/complex',
data: {code:code,encryptedData:encryptedData,iv:iv}, // 設(shè)置請(qǐng)求的 參數(shù)
success: (res) =>{
wx.hideLoading();
that.login();
}
})
}
})
}
})
},
// 獲取用戶信息
getUserInfo:function() {
wx.getUserInfo({
success:(data) =>{
this.globalData.userInfo = data.userInfo;
wx.setStorage({
key: 'userInfo',
data: data.userInfo
})
return this.globalData.userInfo;
}
})
},
globalData:{
userInfo:null,
subDomain:"34vu54u7vuiuvc546d",
token: null
}
})授權(quán)問題

getUserInfo: function () {
// 先調(diào)用wx.getSetting 獲取用戶權(quán)限設(shè)置
wx.getSetting({
success(res) {
console.log('1');
if (!res.authSetting['scope.userInfo']) {
wx.authorize({
scope: 'scope.userInfo',
success() {
// 用戶已經(jīng)同意小程序使用錄音功能,后續(xù)調(diào)用 wx.getUserInfo接口不會(huì)彈窗詢問
wx.getUserInfo({
success: (data) => {
this.globalData.userInfo = data.userInfo;
wx.setStorage({
key: 'userInfo',
data: data.userInfo
})
return this.globalData.userInfo;
}
})
}
})
} else {
console.log(2);
}
}
})
},上述就是小編為大家分享的如何在微信小程序中封裝網(wǎng)絡(luò)請(qǐng)求了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
分享名稱:如何在微信小程序中封裝網(wǎng)絡(luò)請(qǐng)求
當(dāng)前網(wǎng)址:http://chinadenli.net/article8/goisip.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供小程序開發(fā)、微信小程序、網(wǎng)站營銷、Google、全網(wǎng)營銷推廣、微信公眾號(hào)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)