About WeChat applet development user openid save session operation and refactor wx.request integration promise

Recently I received an outsourcing. The client wanted to be a WeChat applet, so when I started building today, I thought about how to build it for later use. For example, I hope that each user will log Each user's request is bound to their own session, and their own openid is stored in the session, so that the server does not need to pass a userid back every time, but only needs to get it through the request.
java code:

	@RequestMapping("/setSession")
	public String getOpenId (String openId, HttpServletRequest request) {
	 	//获取sessionid
		HttpSession session = request.getSession();
		 // 在这个session里存放当前用户的openid,并把sessionid返回
		session.setAttribute("openId", openId);
		return session.getId();
	}
	@RequestMapping("/getOpenId")
	public String getOpenId(HttpServletRequest request) {
		System.out.println(request.getSession().getId());
		return request.getSession().getAttribute("openId").toString();
	}

Small terminal: Then the request here is because the original callback is very troublesome, and I want to use it in the form of a promise callback!

wx.request({
     url: 'http://localhost:8000/setSession',
      data: {
        openId: res.data.openid
      },
success: (res) => {
  // 将此用户的session保存到小程序端,并在每次此用户发起请求时,调用此session
  wx.setStorageSync('sessionid', res.data)
  // 用于测试调用此session获取用户状态
  request.get('/getOpenId',{}).then(res => {
    console.log(res);
  })
}
})

After saving the obtained sessionid in the storage, it is also necessary to bring the
session with each request . Code:

var request = {};
request.options = {
  baseUrl: 'http://localhost:8000'
}

request.get = function (url, data) {
  return new Promise((resovle, reject) => {
    wx.request({
      url: request.options.baseUrl + url,
      dataType: 'json',
      // 去本地里找到sessionid
      header: Object.assign({'Cookie': 'JSESSIONID='+wx.getStorageSync('sessionid')}, {'Cookie': 'JSESSIONID='+wx.getStorageSync('sessionid')}),
      data: data,
      success: function(res) {
        resovle(res);
      },
      fail: function (err) {
        reject(err);
      }
    })
  })
}

module.exports  = request;

In this way, see if each requested session is consistent with the short session of the server

Insert picture description here
Insert picture description here
Insert picture description here
You can see that the three places are the same!
Hope it helps you!

Published 20 original articles · won praise 5 · Views 2069

Guess you like

Origin blog.csdn.net/qq_42859887/article/details/105546952