This is the 16th day of my participation in Gwen Challenge

I learned how to parse and set cookies in Node. Today I started to learn how to set session in Node

Node learning series of articles should be updated after learning every day, but the Dragon Boat Festival before and after more tired, broken more two days, very ashamed!

It seems that insisting on this word has been a long time from me… I hope I can pick it up again

Session

  • The problem of the cookie
    • Sensitive user information may be exposed
  • The solution
    • Cookie stores user insensitive information, and session is set on the server to store user sensitive information

Set the session on the server

app.js

. Const getCookieExpires = () => {const d = new Date() d.setTime() + 24 * 60 * 60 * 1000) return d.toGMTString() } ... // session data const SESSION_DATA = {}... / / parsing cookie the req. Cookies = {} const cookieStr = the req. Headers, cookies | | 'cookieStr. Split ('; ').forEach(item => { if (! item) { return } const arr = item.split('=') const key = arr[0].trim() const val = arr[1].trim() req.cookie[key] = val }) // Set session let neewSetCookie = false Default false let userId = req.cookie.userId // Get userId from cookie // If userId exists if (userId) {// SESSION_DATA[userId] If there is a value, proceed with if (! SESSION_DATA[userId]) {// Set SESSION_DATA[userId] to {} SESSION_DATA[userId] = {}}} else {// No userId exists NeewSetCookie = true // Change neewSetCookie, Set set-cookie userId = '${date.now ()}_${math.random ()}' // Temporarily generate a random userId SESSION_DATA[userId] = {} // Session = SESSION_DATA[userId] // Copy to req.session... // New const blogResult = handleBlogRouter(req, Res) if (blogResult) {blogresult. then(blogData => { Set set-cookie if (neewSetCookie) {res.setheader (' set-cookie ', 'userID =${userID}; path=/; httponly; Expires =${getCookieExpires()} ')} res.end(json.stringify (blogData))}) return} // Handle user routes const userResult = handleUserRouter(req, res) if (userResult) { userResult.then(userData => { console.log('neewSetCookie',neewSetCookie); // Set set-cookie if (neewSetCookie) {res.setheader (' set-cookie ', 'userID =${userID}; path=/; httponly; expires=${getCookieExpires()}`) console.log(9); } res.end(JSON.stringify(userData)) }) return }Copy the code

user.js

  / / login
  if (method == 'POST' && req.path == '/api/user/login') {
    const { username, password } = req.body
    const result = login(username,password)
    return result.then(data= > {
      if(data.username) {
        // res.setHeader('Set-Cookie', `username=${data.username}; path=/; httponly; expires=${getCookieExpires()}`)
        req.session.username = data.username
        req.session.realname = data.realname
        console.log('req.session', req.session);
        return new SuccessModel()
      }
      return new ErrorModel('Login failed ~')})}// Tests for login authentication
  if(method == 'GET' && req.path == '/api/user/login-test') {
    if(req.session.username) {
      return Promise.resolve(new SuccessModel({
        session: req.session
      }))
    }
    return Promise.resolve(new ErrorModel('Not logged in ~'))}}Copy the code

The problem of the session

  • Process memory is limited. If the number of visits is too large, the memory will explode
  • Formal online running may be multi-process, multi-machine and cannot be shared between processes

Session learning is finished today, but it is a little shallow. I feel there will be no problem if I handle logic well. I will continue to update tomorrow