1.添加一个js文件 例如:class/api/Post.js
2.编写js文件 例:token我存在用户信息 17000用户信息过期
3.引用 app.js
4.页面使用
代码:
export default class Post {constructor() { }request = (path, data) => {let app = getApp(),url = `${app.globalData.api}${path}`,header = {token: wx.getStorageSync('user').token || '','content-type': 'application/x-www-form-urlencoded'}var promise = new Promise((resolve, reject) => {wx.request({url: url,data: data,method: "POST",header: header,success(res) {console.log('res 响应拦截', res.data.code)if (res.data.code == 17000) {wx.showModal({title: '提示',content: '授权已过期或未授权!请重新授权!',showCancel: true,cancelText: "返回首页",confirmText: "去授权",success: (res) => {res.cancel ?wx.switchTab({url: '/pages/index/index',}) :wx.navigateTo({url: '/pages/login/login',})},fail: res => { }})}return resolve(res)},fail: reject})});return promise;}}
import Post from './class/api/Post.js'const post = new Post();App({post: post,onLaunch: function () {const updateManager = wx.getUpdateManager()updateManager.onUpdateReady(function () {wx.showModal({title: '更新提示',content: '新版本已经准备好,是否重启应用?',success(res) {if (res.confirm) {// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启updateManager.applyUpdate()}}})})},globalData: {api: Config.api,userInfo: null}})
app.post.request('api', {pageNum: 1,type: 0,lat: 29.03158,lon: 111.69854}).then(res => {console.log('responent', res)})
如果觉得《微信小程序 封装post请求 header加token code码拦截》对你有帮助,请点赞、收藏,并留下你的观点哦!