微信小程序在发送请求时携带cookies问题

我在微信小程序的开发过程中发现如果使用wx.request请求时,请求数据传到后端后是不携带cookie的但是,原因是微信开发工具对wx.request进行修改需要经过微信服务器发送,那么我们后台服务就无法获取到cookie,有些时候也无可避免使用cookie做一些鉴权验证,那怎么办呢。

其实有两种解决方法

1.首先可以通过wx.setStorage将获取的cookie保存到本地

wx.request({
    url: "https://请求路径",
    method: "GET",
    data: {
        account: this.data.account,
        password: this.data.password
    },
    success: (res) => {
        //将请求的数据缓存起来
       wx.setStorage({
       key: 'cookie',
       data: res.cookies,
       success: function () {
          console.log('缓存数据到本地');
       }
    });
   }
})

        然后在调用请求时将刚才缓存的cookie数据丢到header里面一同发送到后台,同时后台再返回cookie继续作缓存

wx.request({
      url: "https://请求路径",
      method: "GET",
      header: {
        'content-type': 'application/json',
        'cookie': wx.getStorageSync('cookie').toString() // 设置cookie不使用tostring会出问题
      },
      data: {
        account: this.data.account,
        password: this.data.password
      },
      success: (res) => {
        wx.setStorageSync("cookie", res.cookies)
        console.log(res)
      }
})

后端代码:

@Autowired
StringRedisTemplate stringRedisTemplate;

@GetMapping("/admin/admingLogin")
    public Admin login(String account, String password, HttpServletRequest req, HttpServletResponse resp){
        String token= CookieUtil.getCookie("admin",req);
        if (token!=null){
            Admin admin= JSON.parseObject(stringRedisTemplate.opsForValue().get(token),Admin.class);
            if(admin!=null)
                CookieUtil.addCookie("admin", token, resp);
                return admin;
        }

        String uuid = String.valueOf(UUID.randomUUID());
        Admin admin = userMapper.login(account, password);
        if(admin==null) return null;
        String value = JSON.toJSONString(admin);
        stringRedisTemplate.opsForValue().set(uuid, value);
        CookieUtil.addCookie("admin", uuid, resp);
        return admin;
}


public static void addCookie(String tokenName,String val,HttpServletResponse resp){
        Cookie cookie=new Cookie(tokenName,val);
        cookie.setMaxAge(3000);
        cookie.setPath("/");
        resp.addCookie(cookie);
    }

第二种方法是使用第三方库weapp-cookie

npm install weapp-cookie --save

# 将 npm 包复制到 vendor 文件夹,避免小程序可能不能找到文件(tips:使用 wepy/mpvue 等框架无需此步)
cp -rf ./node_modules/ ./vendor/
// app.js
import './vendor/weapp-cookie/index'

// tips: 使用 wepy/mpvue 可以直接在入口 js 引入 weapp-cookie 模块
// import 'weapp-cookie'

App({
    onLaunch: function () { }
    // ...
})

启动时可能会报没有定义的错误,请确保dist文件下存在weapp-cookie.js而不为weapp-cookie.es.js,位置完成后直接使用wx.request就能携带cookie请求了

猜你喜欢

转载自blog.csdn.net/a1597133323/article/details/130450930
今日推荐