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

cookie

  • A string stored in the browser (up to 5KB)

  • Not shared across domains

  • The server can modify the cookie and return it to the browser

  • Cookies can also be modified using JS in the browser (with limitations)

    On the client: document.cookie = “// add cookies

The server operates cookies

See the cookie

  / / cookie
  req.cookie = {}
  const cookieStr = req.headers.cookie || ' '
  cookieStr.split('; ').forEach(item= > {
    if(! item) {return
    }
    const arr = item.split('=')
    const key = arr[0]
    const val = arr[1]
    req.cookie[key] = val
  })
  console.log('req.cookie',req.cookie);
Copy the code

Modify the cookie

res.setHeader('Set-Cookie'.`username=${data.username}; path=/`)
Copy the code

Set in the login interface: When the login succeeds, the server returns the cookie to the browser

/ / 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=/`)
        return new SuccessModel()
      }
      return new ErrorModel('Login failed ~')})}Copy the code

Server Settings do not allow clients to change cookie values

res.setHeader('Set-Cookie'.`username=${data.username}; path=/; httponly`)
Copy the code

Gets the cookie expiration time

// Get the cookie expiration time
const getCookieExpires= () = > {
  const d = new Date()
  d.setTime(d.getTime() + 24 * 60 * 60 * 1000)
  return d.toGMTString()
}
/ / set the cookie
res.setHeader('Set-Cookie'.`username=${data.username}; path=/; httponly; expires=${getCookieExpires()}`)
Copy the code

Full document:

router/user.js

const { login } = require('.. /controller/user')
const { SuccessModel, ErrorModel } = require('.. /model/resModel')
// Get the cookie expiration time
const getCookieExpires= () = > {
  const d = new Date()
  d.setTime(d.getTime() + 24 * 60 * 60 * 1000)
  return d.toGMTString()
}
const handleUserRouter = (req, res) = > {
  const method = req.method

  / / 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()}`)
        return new SuccessModel()
      }
      return new ErrorModel('Login failed ~')})}// Tests for login authentication
  if(method == 'GET' && req.path == '/api/user/login-test') {
    if(req.cookie.username) {
      console.log('req.cookie', req.cookie);
      return Promise.resolve(new SuccessModel())
    }
    return Promise.resolve(new ErrorModel('Not logged in ~'))}}module.exports = handleUserRouter

Copy the code

app.js

const querystring = require('querystring')
const handleBlogRouter = require('./src/router/blog.js')
const handleUserRouter = require('./src/router/user.js')

/ / the session data

const SESSION_DATA = {}

// Used to process postData
const getPostData = req= > {
  return new Promise((resolve, reject) = > {
    if(req.method ! = ='POST') {
      resolve({})
      return
    }
    // Non-JSON data type, ignore and return {}
    if (req.headers['content-type'! = ='application/json']) {
      resolve({})
      return
    }
    / / correct
    let postData = ' '
    req.on('data'.chunk= > {
      postData += chunk.toString()
    })
    req.on('end'.() = > {
      if(! postData) { resolve({})return
      }
      // Successful return
      resolve(JSON.parse(postData))
    })
  })
}

const serverHandle = (req, res) = > {
  res.setHeader('Content-Type'.'application/json')

  / / get the path
  const url = req.url
  req.path = url.split('? ') [0]

  / / query
  req.query = querystring.parse(url.split('? ') [1])

  / / cookie
  req.cookie = {}
  const cookieStr = req.headers.cookie || ' '
  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
  })

  / / parse the session
  const userId = req.cookie.userId
  if (userId) {
    if(! SESSION_DATA[userId]) { SESSION_DATA[userId] = {} } }else {
    userId = `The ${Date.now()}_The ${Math.random()}`
    SESSION_DATA[userId] = {}
  }
  req.session = SESSION_DATA[userId]

  / / postData processing
  getPostData(req).then(postData= > {
    req.body = postData
    // Handle old blog routes

    // const blogData = handleBlogRouter(req, res)
    // if (blogData) {
    // res.end(JSON.stringify(blogData))
    // return
    // }

    // Handle blog routing
    const blogResult = handleBlogRouter(req, res)
    if (blogResult) {
      blogResult.then(blogData= > {
        res.end(JSON.stringify(blogData))
      })
      return
    }

    // Process the user route
    // const userData = handleUserRouter(req, res)
    // if (userData) {
    // res.end(JSON.stringify(userData))
    // return
    // }
    const userResult = handleUserRouter(req, res)
    if (userResult) {
      userResult.then(userData= > {
        res.end(JSON.stringify(userData))
      })
      return
    }

    // No route is matched, 404 is returned
    res.writeHead(404, { 'Content-Type': 'text/plain' })
    res.write('404 Not Found\n')
    res.end()
  })
}
module.exports = serverHandle
Copy the code

session

Let’s start with what cookies might expose: sensitive user information

Solution: The cookie stores the userId, and the server corresponds to the username

Session learning has not been completed, there is nothing to say for the moment, and we will update the content after learning

Today I have learned back-end knowledge related to cookie and session, and have a further understanding of cookie and session. Before, because the projects I took over used token for login management, I did not know much about cookie and session. Through today’s learning of cookies basically no problem, tomorrow to do session~