Home  >  Article  >  WeChat Applet  >  How to develop session management in WeChat applet? Tutorial introduction

How to develop session management in WeChat applet? Tutorial introduction

青灯夜游
青灯夜游forward
2020-07-11 17:19:305809browse

How to develop session management in WeChat applet? Tutorial introduction

In the development of WeChat mini programs, each request initiated by wx.request() is a different session for the server. WeChat mini programs will not store session information. Bring it back to the server, which corresponds to different sessions on the server. Since the session is used to save user information in the project, subsequent requests are equivalent to not logging in.

Note that the session here is not the session maintained by the mini program through the wx.login() method, but our own server-side session.

Because under normal circumstances, when the client initiates a request to the server, the session information is stored in the cookie and brought back to the server in the form of a request header, and the specific information in the request header is the session id. As shown in the figure below

How to develop session management in WeChat applet? Tutorial introduction

#The red one is that we need to carry the request header returned to the server when making the request, so what we need is the value of JESSIONID. It just so happens that the WeChat applet also provides support for request headers.

Solution:

1. When the user logs in, the server returns the user's sessionId.

2. The applet saves the sessionId and carries the sessionId in the request header in each subsequent request.

Server key code:

Method to obtain sessionId, just get The request object can be easily obtained

Sting sessionId = request.getSession().getId();

Return the sessionId

...//登录时的业务代码
response.getWriter.write(sessionId);//把sessionId返回给前台

After logging in to the applet, store the sessionId in the global variable. App.js is a good place to store global variables.

...//登录后的逻辑处理
getApp().globalData.header.Cookie = \'JSESSIONID=\' + _data.sessionId;

Code in app.js

globalData:{
header:{\'Cookie\': \'\'} //这里还可以加入其它需要的请求头,比如\'x-requested-with\': \'XMLHttpRequest\'表示ajax提交,微信的请求时不会带上这个的
},

Bring sessionId when requesting the applet

var header = getApp().globalData.header; //获取app.js中的请求头
wx.request({
url: localhost:8080/xx/xx,
header: header, //请求时带上这个请求头
success:function(res){
  }
}

It is recommended to encapsulate your own request information and process some common logic.

Recommendation: " Mini Program Development Tutorial"

The above is the detailed content of How to develop session management in WeChat applet? Tutorial introduction. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete