微信小程序:FLYIO拦截器,获取Token完整代码

安装

首先安装flyio,通过命令:

	npm install flyio -S

例如在request.js中:

	import Fly from 'flyio/dist/npm/wx'
	var fly = new Fly()
	var newfly = new Fly()

请求配置选项

请求配置可以通过fly中的config来设置,例如一些通用配置如下:

	//定义公共headers
	fly.config.headers={
		'content-type': 'application/json',
		'token': 'xxxxxx'
	}
	//设置超时
	fly.config.timeout=10000;
	//设置请求基地址
	fly.config.baseURL="https://你的域名/"

拦截器

	import Fly from 'flyio/dist/npm/wx'
	var fly = new Fly()
	var newfly = new Fly()
	fly.config.baseURL = "https://你的域名/"
	newfly.config.baseURL = "https://你的域名/"
	fly.interceptors.request.use(async function (request) {
	  request.timeout = 30000
	  if (wx.getStorageSync('token') && wx.getStorageSync('token_expiration') > Date.parse(new Date())) {
	    request.headers = {
	      'content-type': 'application/json',
	      'token': wx.getStorageSync('token')
	    }
	  } else {
	    fly.lock()
	    const login = await getToken()
	    wx.setStorageSync('token', login.data.data)
	    wx.setStorageSync('token_expiration', Date.parse(new Date()) + 50000)
	    request.headers = {
	      'content-type': 'application/json',
	      'token': login.data.data
	    }
	    fly.unlock()
	  }
	  return request
	})
	
	fly.interceptors.response.use(async (response) => {
	  return response
	}, (err) => {
	  console.log(err)
	  var title = ''
	  if (err.status === 0) {
	    title = '网络连接异常'
	  } else if (err.status === 1) {
	    title = '网络连接超时'
	  } else if (err.status === 401) {
	    wx.removeStorageSync('token')
	    wx.removeStorageSync('token_expiration')
	    title = '登录超时,请重试'
	  } else {
	    title = err.response.data.message ? err.response.data.message : '请求数据失败,请稍后再试'
	  }
	  return wx.showToast({
	    title: title,
	    icon: 'none',
	    duration: 2000
	  })
	})
	const getToken = async () => {
	  return new Promise((resolve) => {
	    wx.login({
	      async success (loginRes) {
	        console.log(loginRes)
	        if (loginRes.code) {
	          await newfly.get('login/getToken', {
	            code: loginRes.code
	          }).then((flyReq) => {
	            console.log('token请求成功' + flyReq)
	            resolve(flyReq)
	          })
	        } else {
	          console.log('登录失败!' + loginRes.errMsg)
	        }
	      }
	    })
	  })
	}
	export default fly

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值