Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【微信小程序】处理cookie的方法 #18

Open
yaogengzhu opened this issue Aug 21, 2019 · 0 comments
Open

【微信小程序】处理cookie的方法 #18

yaogengzhu opened this issue Aug 21, 2019 · 0 comments

Comments

@yaogengzhu
Copy link
Owner

引用自richard-chou的笔记。

setCookie(cookieStr) {
    const oldCookieJson = this.cookieToJson(wx.getStorageSync('cookie'))
    const newCookieJson = this.multiCookieStrToArray(cookieStr).map((cookieString) => {
      return this.cookieToJson(cookieString)
    }).reduce((result, value) => {
      return Object.assign({}, result, value)
    }, oldCookieJson)
    const newCookieStr = objectEntries(newCookieJson).map(value => value.join('=')).join(';')
    wx.setStorageSync('cookie', newCookieStr)
  },

  cookieToJson(cookieStr) {
    return cookieStr.split(';')
      .filter(value => value.trim())
      .map(value => {
        const equlIndex = value.indexOf('=')
        return [
          value.substr(0, equlIndex),
          value.substr(equlIndex + 1, value.length)
        ]
      }).reduce((result, value) => {
        return Object.assign({}, result, {
          [value[0]]: value[1]
        })
      }, {})
  },

  multiCookieStrToArray(cookieStr) { // 应对 http 响应有多次 set-cookie 的情况
    return cookieStr.split('Path=/,')
  },
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant