The WeChat applet carries cookies when sending requests

During the development process of the WeChat applet, I found that if wx.request is used to request, the request data does not carry cookies after it is transmitted to the backend. However, the reason is that the WeChat development tool needs to send the wx.request through the WeChat server, so Our background service cannot obtain cookies, and sometimes it is unavoidable to use cookies for some authentication and verification, so what should we do?

There are actually two solutions :

1. First, you can save the obtained cookies locally through wx.setStorage

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('缓存数据到本地');
       }
    });
   }
})

        Then when calling the request, the cookie data just cached is thrown into the header and sent to the background together. At the same time, the background returns the cookie to continue caching.

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)
      }
})

Backend code:

@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);
    }

The second method is to use the third-party library 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 () { }
    // ...
})

An undefined error may be reported during startup. Please ensure that weapp-cookie.js exists in the dist file instead of weapp-cookie.es.js. After the location is completed, use wx.request directly to carry the cookie request.

Guess you like

Origin blog.csdn.net/a1597133323/article/details/130450930