天天看點

微信小程式使用Cookie

微信小程式不支援Cookie,是以,需要借助小程式的資料緩存來實作Cookie.

環境: mpvue + fly.js

登入成功後,在處理登入驗證的method裡,加入以下内容儲存Cookie:

wx.setStorageSync("sessionid",response.headers["set-cookie"][0])           

我對fly.js的配置和攔截器單獨設定,放在src/utils/fly.js裡,内容如下:

/**
 * Created by kevin on 2019-10-11.
 * http配置
 */

import store from '@/store/index'
import * as types from '@/store/mutation-types'

var Fly=require("flyio/dist/npm/wx")
var fly=new Fly

// fly配置
fly.config.timeout=5000
// 這個url一定要找到nginx的相應location ^~ 部分
fly.config.baseURL = 'https://i.foo.cn/api/v2/'

// http request 攔截器
fly.interceptors.request.use(
    (request) => {
      if (store.state.user) {
        request.headers.Authorization = `isLogin`
        request.headers.Cookie = wx.getStorageSync("sessionid")
      }
      return request
    },
    err => {
      return Promise.reject(err)
    },
  )
  
// http response 攔截器
fly.interceptors.response.use(
    (response) => {
        //隻将請求結果的data字段傳回
        return response.data
    },
    (err) => {
        //發生網絡錯誤後會走到這裡
        //return Promise.resolve("ssss")
    }
)

export default fly           

然後在全局的main.js裡,加入以下内容:

import fly from '@/utils/fly'

Vue.prototype.$http=fly           

現在可以用this.$http.get(or post等)發起請求了.

萬事大吉,enjoy it!