微信小程序保證sessionid一致

問題發生場景 javascript

註冊功能, 小程序端第一次調用【發送驗證碼】接口, 服務器端將驗證碼存入 session 中。 小程序端第二次調用【註冊】接口, 服務器端接收小程序請求的 sessionid, 經過 sessionid 找到 session, 並判斷驗證碼是否是正確java

問題現象小程序

小程序端兩次請求的 sessionid 不一致, 致使後端沒法取得 session後端

解決辦法api

小程序第一次請求, 從服務器端返回的數據中取得 sessionid, 並存到緩存中或全局變量中緩存

wx.request({
        url: config.api_url,
        data: {
          userPhone: phone
        },
        success: (res) => {
          if (res && res.header && res.header['Set-Cookie']) {
            wx.setStorageSync('cookieKey', res.header['Set-Cookie']); //保存Cookie到Storage
          }
        }
      })

小程序第二次請求時, 從緩存中讀取 sessionid, 並傳遞給服務器端服務器

http.request({
      url: '/xxx',
      header: {
        'Cookie': wx.getStorageSync('cookieKey')
      },
      data: {
        userPhone: phone
      },
      success: (data) => {
        console.log(data)
      }
    })

http 爲封裝的工具類, 主要關注這部分代碼cookie

header: { 'Cookie': wx.getStorageSync('cookieKey') }
相關文章
相關標籤/搜索