小程序中封装ajax请求,如何在微信小程序中封装网络请求

如何在微信小程序中封装网络请求

发布时间:2021-05-11 16:59:36

来源:亿速云

阅读:95

作者:Leah

这期内容当中小编将会给大家带来有关如何在微信小程序中封装网络请求,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

网络请求

网络请求小程序提供了wx.request, 仔细看一下api,这不就是n年前的 $.ajax 吗,好古老啊。// 官方例子

wx.request({

url: 'test.php', //仅为示例,并非真实的接口地址

data: {

x: '' ,

y: ''

},

header: {

'content-type': 'application/json' // 默认值

},

success: function(res) {

console.log(res.data)

}

})

小程序支持ES6,那么就应该支持Promise 了,很开心~, 话不多说直接上代码吧

Promise封装const baseUrl = 'https://api.it120.cc';

const http = ({ url = '', param = {}, ...other } = {}) => {

wx.showLoading({

title: '请求中,请耐心等待..'

});

let timeStart = Date.now();

return new Promise((resolve, reject) => {

wx.request({

url: getUrl(url),

data: param,

header: {

'content-type': 'application/json' // 默认值 ,另一种是 "content-type": "application/x-www-form-urlencoded"

},

...other,

complete: (res) => {

wx.hideLoading();

console.log(`耗时${Date.now() - timeStart}`);

if (res.statusCode >= 200 && res.statusCode 

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')

// 单个请求

api.get('list').then(res => {

console.log(res)

}).catch(e => {

console.log(e)

})

// 一个页面多个请求

Promise.all([

api.get('list'),

api.get(`detail/${id}`)

]).then(result => {

console.log(result)

}).catch(e => {

console.log(e)

})

登陆问题

做一个应用,肯定避免不了登录操作。用户的个人信息啊,相关的收藏列表等功能都需要用户登录之后才能操作。一般我们使用token做标识。

小程序并没有登录界面,使用的是wx.login。 wx.login会获取到一个 code,拿着该 code去请求我们的后台会最后返回一个token到小程序这边,保存这个值为 token 每次请求的时候带上这个值。

一般还需要把用户的信息带上比如用户微信昵称,微信头像等,这时候就需要使用 wx.getUserInfo ,这里涉及到一个用户授权的问题

带上用户信息就够了嘛? too young too simple!我们的项目不可能只有小程序,相应的微信公众平台可能还有相应的App,我们需要把账号系统打通,让用户在我们的项目中的账户是同一个。这就需要用到微信开放平台提供的 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】调用微信自带登陆

wx.login({

success: function (res) {

// 【2】 拿到code去访问我们的后台换取其他信息

wx.request({

url: 'https://api.it120.cc/'+ that.globalData.subDomain +'/user/wxapp/login',

data: {

code: res.code

},

success: function(res) {

// 如果说这个code失效的

if (res.data.code == 10000) {

// 去注册

that.registerUser();

return;

}

// 如果返回失败了

if (res.data.code != 0) {

// 登录错误

wx.hideLoading();

// 提示无法登陆

wx.showModal({

title: '提示',

content: '无法登录,请重试',

showCancel:false

})

return;

}

// 【3】 如果成功后设置token到本地

that.globalData.token = res.data.data.token;

// 保存用户信息

wx.setStorage({

key: 'token',

data: res.data.data.token

})

}

})

}

})

},

// 注册?? [这个看需求]

registerUser: function () {

var that = this;

wx.login({

success: function (res) {

var code = res.code; // 微信登录接口返回的 code 参数,下面注册接口需要用到

wx.getUserInfo({

success: function (res) {

var iv = res.iv;

var encryptedData = res.encryptedData;

// 下面开始调用注册接口

wx.request({

url: 'https://api.it120.cc/' + that.globalData.subDomain +'/user/wxapp/register/complex',

data: {code:code,encryptedData:encryptedData,iv:iv}, // 设置请求的 参数

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

}

})

授权问题

5a6fde9b0f4b5faf39f60e549ca4ee20.pnggetUserInfo: function () {

// 先调用wx.getSetting 获取用户权限设置

wx.getSetting({

success(res) {

console.log('1');

if (!res.authSetting['scope.userInfo']) {

wx.authorize({

scope: 'scope.userInfo',

success() {

// 用户已经同意小程序使用录音功能,后续调用 wx.getUserInfo接口不会弹窗询问

wx.getUserInfo({

success: (data) => {

this.globalData.userInfo = data.userInfo;

wx.setStorage({

key: 'userInfo',

data: data.userInfo

})

return this.globalData.userInfo;

}

})

}

})

} else {

console.log(2);

}

}

})

},

上述就是小编为大家分享的如何在微信小程序中封装网络请求了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值