SoFunction
Updated on 2025-03-01

Session management of http requests for WeChat applets

Session management of http requests for WeChat applets

As a programmer who develops Java Web applications, they like to put the user information (such as user ID and user name) after the user is logged in into the session, and then when user information is needed in the development of business logic, they can easily and conveniently get the value from the session. Recently, I encountered a problem when developing WeChat mini programs. Every time the WeChat mini program requests, the sessionid will be changed, which will cause the user information saved in the session when login cannot be retrieved in the subsequent request. In fact, this problem will also be encountered when the front and back ends are separated and sent. The backend programmer is responsible for server-side development and provides interface programs, and the front-end programmer is responsible for client development, and calls the interface program provided by the back-end programmer to obtain data. At this time, each interface program requested by the front-end programmer will also change the sessionid, because it is impossible to obtain the user information saved in the session when logging in.

The common way to keep session is that when the browser initiates an http request to the server, the server checks whether the sessionid is included in the http header cookie parameter. If there is a sessionid, check the session stored on the server based on the sessionid and some information about the current session stored in the session. If the sessionid does not have a server, it will be assigned one and written to the cookie field. The browser will bring it with you the next time it initiates other requests.

Therefore, in order to solve the problem I mentioned above, we can do this. When the client first requests the server, that is, when logging in, it will store it locally, and then every time the server is requested, it will bring this sessionid in the header and write it into the cookie field. But there is a problem that after you store this sessionid locally, it will be this sessionid every time in the future. Therefore, it is recommended to clear the locally stored sessionid when the program is started, and then send the first request to get the new sessionid.

The following is the client code with sessionid in the header when requesting ajax:

$.ajax({
      type: 'post',
      headers: {
        'Cookie':'JSESSIONID=1k2naixut68f81q5rpr0c3n4vc'
      },
      data: {},
      dataType: 'json',
      timeout: 30000,
      url: '/test',
      success: function (res) {
        alert("success");
      },
      error: function (e) {
        alert("false");
      }
    })

Thank you for reading, I hope it can help you. Thank you for your support for this site!