小程序中登陆保持解决方案

2022年9月7日 06:20 by wst

小程序

小程序开发,咋一看有很多限制,其实传统的网页开发基本类似。

下面以我最近遇到的问题,总结下登陆的解决方案。

目标

1.让服务器知道,用户已经登陆且未失效。

2.让前端知道,自己的登陆是否过期。

解决方案

1. 利用微信的登陆获取登陆后的cookie,并写入缓存。

调用微信登陆--》成功后调用自己的登陆--》登陆后把cookie和有效期写入storage--》每次请求检查是否过期--》如过期再次重复之前的步骤。

2. 利用服务端的session机制,记录是否登陆过期。

判断session失效后返回登陆过期--》前端受到过期后再次调用上面的登陆流程

实现步骤

1. 启动过程中的鉴权(app.js):

import {
  request
} from "./request/index";

onLaunch: function () {
    // 判断登录是否失效
    var sessionId =wx.getStorageSync('session') || 'nosession'
    var expiredTime =wx.getStorageSync('expired') || 0
    console.log("session:" + sessionId + ", expired:" + expiredTime)
    var now = new Date()
    // 未过期,直接进入页面
    if (now < expiredTime) { 
      console.log("登录未失效")
      this.globalData.session = sessionId
      this.globalData.expired = expiredTime
      // 取出缓存中的数据,并赋值给全局变量
      var data = wx.getStorageSync('data')
      this.globalData.uid = data.uid
      this.globalData.role = data.role
    } else {
      console.log("登录已过期")
      this.getLoginInfo()        // 过期了,需要重新登录
    }

  },

2. 登陆过程

getLoginInfo() {
    wx.login({  // 登录
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        request({
          url: '/user/wx/login',
          method: 'POST',
          data: {
            code: res.code
          },
        }).then(
          res => {
            console.log("logined data:", res)
            this.globalData.uid = res.data.uid
            this.globalData.role = res.data.role
            wx.setStorageSync('data', res.data)
          }
        ).catch(
          (errMsg)=>{console.log("error ...", errMsg);}
        )
      },
      fail: res=>{
        console.log("login error", res)
      }
    })
  },

3. 封装微信的原始请求(request/index.js)

import {
  BASE_URL
} from '../config'

// 同时发送异步代码的次数
let ajaxTimes = 0;
export const request = (params) => {
  // 判断 url中是否带有 /my/ 请求的是私有的路径 带上header token
  let header = {
    ...params.header
  };

  // 拼接header 带上token
  header["session"] = wx.getStorageSync('session') || 'nosession';
  ajaxTimes++;
  // 显示加载中 效果
  wx.showLoading({
    title: "加载中...",
    mask: true
  });


  // 封装原始请求
  return new Promise((resolve, reject) => {
    wx.request({
      ...params,
      header: header,
      url: BASE_URL + params.url,
      timeout: 30000,
      success: (result) => {
        resolve(result.data);
        if (params.url.includes("/user/wx/login")) {
          // 把登录返回的session写入缓存
          console.log("登录cookie已写入缓存")
          wx.setStorageSync('session', result.header.session)
          wx.setStorageSync('expired', result.header.expired)
        }
        if (result.data.code === 6) {
          console.log("url:", params.url)
          // 处理登录过期的情况
          login()
        }
      },
      fail: (err) => {
        console.log("request error:", err)
        reject(err);
      },
      complete: () => {
        ajaxTimes--;
        if (ajaxTimes === 0) {
          //  关闭正在等待的图标
          wx.hideLoading();
        }
      }
    });
  })
}

export const login = () => {
  wx.login({
    success: res => {
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      request({
        url: '/user/wx/login',
        method: 'POST',
        data: {
          code: res.code
        },
      }).then(res => {
        var app = getApp()
        console.log("logined[single] data:", res.data)
        wx.setStorageSync('data', res.data)
        app.globalData.uid = res.data.uid
        app.globalData.role = res.data.role
        wx.reLaunch({
          url: '/pages/welcome/welcome',
        })
      })
    }

  })
}

关于具体实现,如有问题可评论,进一步讨论。


Comments(125) Add Your Comment

Swuinx
buy lipitor generic <a href="https://lipiws.top/">order atorvastatin 10mg</a> buy atorvastatin 40mg online cheap
Ykplxe
ciprofloxacin 1000mg canada - <a href="https://cipropro.top/">cipro 500mg over the counter</a> buy clavulanate no prescription
Gonaej
cipro oral - <a href="https://metroagyl.top/keflexcapsule/">keflex 125mg cheap</a> augmentin 625mg sale
Rosojk
flagyl generic - <a href="https://metroagyl.top/cefaclor/">cefaclor usa</a> azithromycin 500mg generic
Kamnza
ciprofloxacin 500mg price - <a href="https://septrim.top/erythromycin/">order generic erythromycin 250mg</a> erythromycin 500mg us
Dewahs
ivermectin uk - <a href="https://keflexin.top/tetracycline/">order sumycin 500mg online</a> buy cheap tetracycline
Tprdiv
valacyclovir usa - <a href="https://gnantiviralp.com/zovirax/">cost zovirax</a> zovirax brand
Nrviqg
order flagyl 400mg - <a href="https://metroagyl.top/">generic metronidazole</a> buy zithromax sale
Vahujp
buy ampicillin no prescription <a href="https://ampiacil.top/amoxil500/">order amoxil generic</a> buy amoxil for sale
Gyjbus
buy furosemide 40mg sale - <a href="https://antipathogenc.com/prograf/">prograf 1mg tablet</a> buy captopril generic
Rxzdhb
order generic glucophage 500mg - <a href="https://gnantiacidity.com/lincocin/">purchase lincocin sale</a> order lincomycin online
Eximjz
generic retrovir - <a href="https://canadiangnp.com/epivir/">epivir 100mg sale</a> allopurinol oral
Tyuxmc
clozapine for sale online - <a href="https://genonlinep.com/accupril/">order accupril 10 mg pill</a> order famotidine
Idumru
quetiapine drug - <a href="https://gnkantdepres.com/effexor/">oral venlafaxine 75mg</a> buy eskalith tablets
Swpdjb
order generic anafranil 50mg - <a href="https://antdeponline.com/celexa/">order celexa 40mg generic</a> generic doxepin 25mg
Edzdut
hydroxyzine brand - <a href="https://antdepls.com/prozac/">brand fluoxetine 40mg</a> buy endep 25mg pills
Armekv
augmentin pills - <a href="https://atbioinfo.com/septra/">buy bactrim tablets</a> ciprofloxacin 1000mg us
Tpvver
amoxicillin canada - <a href="https://atbioxotc.com/cefadroxil/">order cefadroxil sale</a> ciprofloxacin 500mg brand
Doflvc
buy zithromax 500mg pill - <a href="https://gncatbp.com/btetracycline/">sumycin uk</a> ciprofloxacin 500 mg us
Jyyqvo
cleocin where to buy - <a href="https://cadbiot.com/oxytetracycline/">order oxytetracycline 250 mg online cheap</a> chloromycetin pills
Nfeluw
india ivermectin - <a href="https://antibpl.com/">ivermectin 3 mg pills for humans</a> cefaclor 500mg price
Ljskxe
albuterol usa - <a href="https://antxallergic.com/cvallegra/">order allegra for sale</a> purchase theophylline for sale
Hrgxhu
medrol 8mg without prescription - <a href="https://ntallegpl.com/getcetirizine/">cost cetirizine</a> astelin uk
Bswvld
clarinex 5mg sale - <a href="https://rxtallerg.com/ventolinpill/">order albuterol generic</a> purchase ventolin pills
Qesmmp
micronase 2.5mg without prescription - <a href="https://prodeprpl.com/dapagliflozin5/">forxiga 10 mg canada</a> order dapagliflozin 10mg pills
Zogjhy
glucophage 500mg canada - <a href="https://arxdepress.com/acarbose50/">order acarbose 25mg without prescription</a> buy acarbose no prescription
Knhrql
prandin brand - <a href="https://depressinfo.com/">order prandin 2mg pills</a> cost jardiance 10mg
Wepquv
buy generic lamisil 250mg - <a href="https://treatfungusx.com/xgrifulvinvs/">buy griseofulvin no prescription</a> buy grifulvin v for sale
Jzzqqe
semaglutide us - <a href="https://infodeppl.com/">buy rybelsus pills for sale</a> desmopressin usa
Zmnvkv
order ketoconazole 200 mg without prescription - <a href="https://antifungusrp.com/butenafinecream/">purchase mentax for sale</a> buy generic sporanox online
Djumpf
buy generic famciclovir for sale - <a href="https://amvinherpes.com/acyclovircream/">acyclovir 800mg pills</a> purchase valaciclovir sale
Jotvcb
lanoxin 250 mg us - <a href="https://blpressureok.com/isoptinpillmg/">calan pills</a> lasix pills
Kmnesp
microzide 25 mg price - <a href="https://norvapril.com/felodipine/">order felodipine without prescription</a> zebeta medication
Ycefnr
metoprolol 50mg tablet - <a href="https://bloodpresspl.com/">order metoprolol 100mg generic</a> buy nifedipine 30mg for sale
Paazhb
nitroglycerin cheap - <a href="https://nitroproxl.com/valsartan/">valsartan 80mg drug</a> diovan canada
Cswcho
rosuvastatin pills dinner - <a href="https://antcholesterol.com/pravastatin/">pravachol buy twelve</a> caduet step
Qqfetk
zocor coin - <a href="https://canescholest.com/fenofibrate/">tricor cost</a> atorvastatin fetch
Fixshc
viagra professional online chuckle - <a href="https://edsildps.com/cialisprofessional/">buy cialis professional quiet</a> levitra oral jelly catch
Xitqec
dapoxetine insult - <a href="https://promedprili.com/cialiswithdapoxetine/">cialis with dapoxetine overhead</a> cialis with dapoxetine lover
Fojvzf
cenforce father - <a href="https://xcenforcem.com/brandviagrasildenafil/">brand viagra utmost</a> brand viagra pills claw
Wppgyt
brand cialis worry - <a href="https://probrandtad.com/penisole/">penisole glisten</a> penisole off
Xvvrbg
cialis soft tabs pills torture - <a href="https://supervalip.com/tadarisepills/">tadarise pills seven</a> viagra oral jelly surface
Yxxjrr
brand cialis blaze - <a href="https://probrandtad.com/brandlevitra/">brand levitra sometime</a> penisole powder
Ygrjds
cialis soft tabs rise - <a href="https://supervalip.com/valifonline/">valif absorb</a> viagra oral jelly online dare
Pibprl
acne medication pound - <a href="https://placnemedx.com/">acne medication room</a> acne medication pillar
Iiwlkc
asthma treatment attach - <a href="https://bsasthmaps.com/">asthma treatment snort</a> asthma treatment shriek
Xofcpe
uti medication listen - <a href="https://amenahealthp.com/">treatment for uti peace</a> uti antibiotics recognize
Bkites
pills for treat prostatitis develop - <a href="https://xprosttreat.com/">pills for treat prostatitis pride</a> prostatitis pills salt
Zxjjus
claritin without - <a href="https://clatadine.top/">claritin extent</a> claritin pills success
Yaczxd
valtrex believe - <a href="https://gnantiviralp.com/">valtrex pills tail</a> valacyclovir online meat
Javbeu
priligy robe - <a href="https://prilixgn.top/">dapoxetine cluster</a> dapoxetine park
Xbpfdy
loratadine himself - <a href="https://clatadine.top/">loratadine medication lore</a> claritin pills mission
Wqegjf
ascorbic acid smaller - <a href="https://ascxacid.com/">ascorbic acid stalk</a> ascorbic acid crumble
Tiedwj
promethazine agree - <a href="https://prohnrg.com/">promethazine mad</a> promethazine art
Rqwwsp
biaxin misty - <a href="https://gastropls.com/gncytotec/">cytotec exercise</a> cytotec often
Lxmcps
florinef pills almost - <a href="https://gastroplusp.com/omepprilosec/">prilosec pills trust</a> lansoprazole pills exercise
Uxzdke
buy rabeprazole 20mg pills - <a href="https://gastrointesl.com/domperidone/">purchase motilium pills</a> how to get motilium without a prescription
Lyqxgs
buy dulcolax generic - <a href="https://gastroinfop.com/liv52/">liv52 20mg cost</a> buy liv52 pill
Qncjqm
zovirax sale - <a href="https://dupsteron.com/">order duphaston without prescription</a> duphaston 10mg uk
Cuuqge
order cotrimoxazole 480mg generic - <a href="https://tobmycin.com/">purchase tobramycin online cheap</a> buy tobra 5mg online
Shncze
griseofulvin 250 mg generic - <a href="https://dipyrilx.com/">order dipyridamole 100mg for sale</a> order gemfibrozil 300mg sale
Yddgke
order forxiga online - <a href="https://sineqpin.com/">doxepin 75mg canada</a> purchase acarbose generic
Dbjqur
dramamine order online - <a href="https://bisacolax.com/">buy generic dimenhydrinate</a> buy actonel 35 mg without prescription
Ehghas
buy vasotec 10mg for sale - <a href="https://xalanoprost.com/">buy generic xalatan</a> order latanoprost without prescription
Ngvyjf
order etodolac online - <a href="https://etodograph.com/">buy etodolac generic</a> order cilostazol 100 mg
Namfwg
buy feldene sale - <a href="https://feldexicam.com/">order piroxicam for sale</a> purchase exelon online
Wptrvb
buy nootropil 800 mg generic - <a href="https://nootquin.com/">order piracetam generic</a> buy sinemet sale
Mujepz
how to buy hydroxyurea - <a href="https://hydroydrinfo.com/pentoxifylline/">buy trental sale</a> robaxin canada
Axpjgv
order divalproex online cheap - <a href="https://adepamox.com/aspirindipyridamole/">aggrenox ca</a> topamax 200mg over the counter
Vwtggi
purchase disopyramide phosphate pill - <a href="https://anorpica.com/pregabal/">pregabalin 75mg cost</a> order thorazine 50 mg generic
Lykbmu
cyclophosphamide online - <a href="https://cycloxalp.com/dimenhydrinate/">dramamine uk</a> how to buy vastarel
Pmfiap
buy spironolactone pills - <a href="https://aldantinep.com/naltrexone/">revia 50mg us</a> revia 50mg over the counter
Udvnom
buy cheap cyclobenzaprine - <a href="https://abflequine.com/enalapril/">vasotec for sale</a> enalapril generic
Xhqvpm
buy zofran no prescription - <a href="https://azofarininfo.com/tolterodine/">order tolterodine online</a> requip price
Deacsk
ascorbic acid 500 mg sale - <a href="https://mdacidinfo.com/">buy ascorbic acid for sale</a> prochlorperazine where to buy
Kgtidi
order durex gel for sale - <a href="https://xalaplinfo.com/">order durex gel for sale</a> buy latanoprost without prescription
Zpafrq
purchase minoxidil online cheap - <a href="https://hairlossmedinfo.com/finasteridehl/">order propecia 5mg</a> order finasteride 5mg generic
Kjrmxd
leflunomide 10mg drug - <a href="https://infohealthybones.com/cartidin/">cheap cartidin</a> cartidin online
Eyyrlc
order calan 240mg without prescription - <a href="https://infoheartdisea.com/atenolol/">buy generic tenoretic over the counter</a> cheap tenoretic sale
Hfsamp
buy tenormin 50mg for sale - <a href="https://heartmedinfox.com/carvedilol/">buy carvedilol</a> buy coreg 6.25mg sale
Kvtvoj
buy atorlip online - <a href="https://infoxheartmed.com/nebivolol/">bystolic 20mg cheap</a> cheap nebivolol 20mg
Hmasjr
buy gasex generic - <a href="https://herbalinfomez.com/">buy generic gasex</a> buy generic diabecon for sale
Erfyag
buy generic lasuna - <a href="https://infoherbalmz.com/himcolin/">himcolin medication</a> order himcolin generic
Llagup
buy cheap noroxin - <a href="https://gmenshth.com/">noroxin over the counter</a> cost confido
Awkeae
finasteride drug - <a href="https://finmenura.com/kamagra/">buy kamagra pills</a> order alfuzosin online cheap
Kzwhvd
buy terazosin - <a href="https://hymenmax.com/dutasteride/">order generic avodart</a> order priligy 90mg pills
Rdbafx
speman tablets - <a href="https://spmensht.com/finasteride/">buy fincar cheap</a> purchase finasteride sale
Ciaili
buy generic oxcarbazepine over the counter - <a href="https://trileoxine.com/pirfenidone/">pirfenex pills</a> levothyroxine cost
Sbngnj
buy generic cyclosporine over the counter - <a href="https://asimusxate.com/methotrexate/">cheap methotrexate 5mg</a> cost gloperba
Memltk
duphalac us - <a href="https://duphalinfo.com/mentat/">buy generic mentat</a> buy betahistine tablets
Rhdkhw
calcort sale - <a href="https://lazacort.com/">purchase calcort online</a> buy alphagan generic
Lfvuam
order besifloxacin without prescription - <a href="https://besifxcist.com/sildamax/">cheap sildamax online</a> sildamax drug
Ciaxab
buy gabapentin online - <a href="https://aneutrin.com/sulfasalazine/">buy sulfasalazine 500mg generic</a> sulfasalazine 500mg drug
Torapo
order probenecid - <a href="https://bendoltol.com/monograph/">buy etodolac no prescription</a> order carbamazepine 400mg pills
Kiiiof
generic celebrex 200mg - <a href="https://celespas.com/">buy celecoxib online cheap</a> order generic indomethacin
Dunpdi
colospa 135 mg canada - <a href="https://coloxia.com/">buy mebeverine 135 mg online cheap</a> pletal 100 mg cheap
Yaodkh
cambia order - <a href="https://dicloltarin.com/">cambia over the counter</a> oral aspirin 75mg
Xufprc
buy rumalaya generic - <a href="https://rumaxtol.com/">how to get rumalaya without a prescription</a> elavil canada
Pkdhsx
order generic mestinon 60 mg - <a href="https://mestonsx.com/azathioprine/">azathioprine 50mg usa</a> imuran 25mg tablet
Kbeovd
order voveran sale - <a href="https://vovetosa.com/animodipine/">buy nimodipine sale</a> buy nimodipine no prescription
Bycjjb
buy ozobax paypal - <a href="https://baclion.com/">purchase baclofen without prescription</a> order feldene 20 mg for sale
Fhaloy
buy meloxicam medication - <a href="https://meloxiptan.com/">meloxicam 7.5mg pill</a> toradol online
Ezalqm
periactin order - <a href="https://periheptadn.com/aszanaflex/">purchase tizanidine sale</a> generic zanaflex
Hijvkv
buy artane online - <a href="https://voltapll.com.com/">buy artane paypal</a> diclofenac gel where to order
Lnctwg
omnicef online buy - <a href="https://omnixcin.com/aminocycline/"></a> buy cheap generic cleocin
Slbbdv
order accutane 10mg generic - <a href="https://aisotane.com/asdeltasone/">deltasone 5mg brand</a> deltasone ca
Qxfdxd
order prednisone 20mg sale - <a href="https://apreplson.com/permethrin/">buy elimite sale</a> elimite oral
Eyndwb
permethrin medication - <a href="https://actizacs.com/tretinoin/">tretinoin online buy</a> buy tretinoin gel sale
Odhhnc
metronidazole 400mg cost - <a href="https://cenforcevs.com/">brand cenforce 50mg</a> order cenforce generic
Kqsfps
amoxiclav without prescription - <a href="https://baugipro.com/">augmentin medication</a> order synthroid 100mcg generic
Zkcfqf
cleocin 150mg ca - <a href="https://indometnp.com/">purchase indocin for sale</a> cost indomethacin 50mg
Waarfs
cozaar tablet - <a href="https://cozartan.com/">losartan 50mg generic</a> purchase cephalexin generic
Chflrx
crotamiton medication - <a href="https://aeuracream.com/">buy eurax generic</a> buy generic aczone for sale
Espjjx
provigil over the counter - <a href="https://sleepagil.com/phenergan/">order promethazine 25mg pill</a> generic melatonin 3 mg
Qdbwcm
order zyban 150 mg - <a href="https://bupropsl.com/shuddhaguggulu/">order shuddha guggulu online cheap</a> cheap shuddha guggulu pill
Ncdtkm
buy capecitabine generic - <a href="https://xelocap.com/danocrine/">order generic danazol 100 mg</a> buy generic danocrine 100mg
Nlzrex
prometrium 100mg generic - <a href="https://apromid.com/gynelotrimin/">purchase ponstel online</a> cheap clomiphene
Gtrphf
buy alendronate 70mg sale - <a href="https://pilaxmax.com/tamoxifen/">tamoxifen cheap</a> order provera without prescription
Myjhkv
aygestin without prescription - <a href="https://norethgep.com/bimatoprost/">order bimatoprost generic</a> yasmin price
Pcouky
estradiol price - <a href="https://festrolp.com/anastrozole/">order generic anastrozole 1mg</a> buy anastrozole 1mg
Kbtwjv
cabergoline generic - <a href="https://adostilin.com/premarin/">order premarin 0.625mg without prescription</a> order alesse generic
Bbfusx
プレドニン通販 - <a href="https://jpaonlinep.com/">プレドニン通販 安全</a> アジスロマイシン錠 500mg 強さ
Mljick
バイアグラの飲み方と効果 - <a href="https://jpedpharm.com/tadalafil/">シアリスジェネリック 通販</a> タダラフィルジェネリック 通販
Flncwl
正規品プレドニン錠の正しい処方 - <a href="https://jpanfarap.com/">プレドニン 市販 おすすめ</a> イソトレチノイン錠 40 mg 強さ
Zxwgkl
eriacta weak - <a href="https://eriagra.com/asildigrah/">sildigra weep</a> forzest natural