123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- const Fly = require("../lib/wx.umd.min") //wx.js is your downloaded code
- const fly = new Fly(); //Create an instance of Fly
- const app = getApp()
- //设置超时
- fly.config.timeout = 20000;
- // 获取白名单
- import whiteList from './whiteList';
- // Add interceptors
- fly.interceptors.request.use((request) => {
- // console.log('进入fly-request', request);
- wx.showLoading({
- 'title': '加载中',
- 'mask': true
- });
- // 不显示加载页面的接口
- if (request.url.indexOf(whiteList.loading) === -1) {
- // 隐藏loading遮罩
- wx.hideLoading();
- }
- // 请求资源服务器时,不添加token
- if (request.url.indexOf(whiteList.nullHeaderToken) !== -1) {
- request.timeout = 30000; // 请求超时
- request.headers = {
- 'content-type': 'application/json',
- 'X-Tag': 'flyio'
- };
- console.log('nullHeaderToken()')
- return request;
- }
- // fly.lock()
- // 延迟发请求 等 getStorageSync 存储
- if (request.headers.Authorization) {
- // 给所有请求添加自定义header
- request.timeout = 30000;
- Object.assign(request.headers, {
- 'content-type': 'application/json',
- 'X-Tag': 'flyio'
- })
- // fly.unlock(); //解锁请求
- return request;
- }
- if(wx.getStorageSync('token')) {
- // 给所有请求添加自定义header
- request.timeout = 30000;
- Object.assign(request.headers, {
- 'content-type': 'application/json',
- 'X-Tag': 'flyio',
- 'Authorization': `Bearer ${wx.getStorageSync('token')}`
- })
- // fly.unlock(); //解锁请求
- return request;
- }
- // else if(!wx.getStorageSync('token')&&app.getCurrentPages()=='pages/login/login') {
- // request.headers = {
- // 'content-type': 'application/json',
- // 'X-Tag': 'flyio',
- // 'Authorization': 'Basic dGVzdDp0ZXN0'
- // };
- // fly.unlock();//解锁请求
- // return request;
- // }
- else {
- console.log(app.getCurrentPages())
- }
- }, (error, promise) => {
- // Do something with request error
- console.log(error); // for debug
- promise.reject(error)
- });
- fly.interceptors.response.use(
- (response) => {
- wx.hideLoading();
- //只将请求结果的data字段返回
- return response
- },
- (err, promise) => {
- wx.hideLoading();
- let msg = '';
- if (err.status === 0) {
- msg = '网络连接异常'
- } else if (err.status === 1) {
- msg = '网络连接超时'
- } else if (err.status === 401) {
- msg = '用户未登录'
- wx.clearStorageSync('token')
- // wx.navigateTo({
- // url: 'pages/me/me'
- // });
- } else {
- if (err.response.data.message) {
- msg = err.response.data.message
- } else {
- msg = '请求数据失败,请稍后再试'
- }
- }
- wx.showToast({
- title: msg,
- icon: 'none',
- duration: 3000
- });
- // setTimeout(() => {
- // console.log('fly.interceptors.err-toLogin')
- // wx.redirectTo({
- // url: '../login/login'
- // });
- // }, 500)
- return promise.resolve(err)
- }
- )
- // Set the base url
- fly.config.baseURL = "https://wx.sgsino.cn"
- export default fly;
|