美文网首页
Cookie,Session,localStorage

Cookie,Session,localStorage

作者: BOB_BI | 来源:发表于2019-03-27 17:37 被阅读0次

Cookie

  1. 服务器通过 Set-Cookie 头给客户端一串字符串
  2. 客户端每次访问相同域名的网页时,必须带上这段字符串
  3. 客户端要在一段时间内保存这个Cookie
  4. Cookie 默认在用户关闭页面后就失效,后台代码可以任意设置 Cookie 的过期时间
  5. 大小大概在 4kb 以内

获取到请求头中的数据


image.png

decodeURIComponent() //方法用于解码,由 encodeURIComponent方法或者其它类似方法编码的部分统一资源标识符(URI)。@ %40
401字段认证失败
登录成功set-cookie。


image.png
cookie 特点:
1.服务器通过set-cookie响应头设置cookie

2.浏览器的到cookie后,每次请求都带上cookie
3.服务器读取cookie就知道登录用户的信息

问题:
1.cookie存在哪?
c盘的一个文件
2.cookie可随意更改


image.png

cookie不安全
3.不同浏览器,失效
4.cookie有效期
默认有效期20分钟左右,浏览器决定


image.png
页面中获取:document.cookie
node中获取cookie:request.headers.cookie
response.setHeader('Set-Cookie','<cookie-name>=<cookie-value>')
设置httponly使js不可更改cookie

编写一个完整的登录注册功能

注册思路:
1.页面输入用户名,密码,重复密码,jQuery.post发送请求
2.服务器拿到这些字段,通过split('&'),split('='),分解并存入一个hash中,必要时使用decodeURIComponent(value)处理hash中的value
3.读取数据库中的字段
fs.readFileSync('表路径', 'utf8')
验证请求的字段是否存在,不存在则
fs.writeFileSync('数据库表路径',data)
4.页面错误提示

 $.post('/sign_up', hash)  
        .then((response)=>{
          console.log(response)
        }, (request)=>{
          let {errors} = request.responseJSON
          if(errors.email && errors.email === 'invalid'){
            $form.find('[name="email"]').siblings('.error')
              .text('邮箱格式错误')
          }
        })

登录思路:
1.页面输入用户名,密码,发送请求
2.获取请求体,过split('&'),split('='),分解并存入一个hash中

else if(path==='/sign_in' && method === 'POST'){
    readBody(request).then((body)=>{
      let strings = body.split('&') // ['email=1', 'password=2', 'password_confirmation=3']
      let hash = {}
      strings.forEach((string)=>{
        // string == 'email=1'
        let parts = string.split('=') // ['email', '1']
        let key = parts[0]
        let value = parts[1]
        hash[key] = decodeURIComponent(value) 
      })

3.读取数据库中的所有字段,与2对比,如果匹配则set一个cookie

  let {email, password} = hash
      var users = fs.readFileSync('./db/users', 'utf8')
      try{
        users = JSON.parse(users) // []
      }catch(exception){
        users = []
      }
      let found
      for(let i=0;i<users.length; i++){
        if(users[i].email === email && users[i].password === password){
          found = true
          break
        }
      }
      if(found){
        response.setHeader('Set-Cookie', `sign_in_email=${email}`)
        response.statusCode = 200
      }else{
        response.statusCode = 401
      }
      response.end()
    })

4.登录成功则跳转,失败则提示

$.post('/sign_in', hash)  
        .then((response)=>{
          window.location.href = '/'
        }, (request)=>{
          alert('邮箱与密码不匹配')
        })

Session

实质:服务器上的hash表
1.将 SessionID(随机数)通过 Cookie 发给客户端
2.客户端访问服务器时,服务器读取 SessionID
3.服务器有一块内存(哈希表)保存了所有 session
4.通过 SessionID 我们可以得到对应用户的隐私信息,如 id、email
5.这块内存(哈希表)就是服务器上的所有 session

localStorage

html5提供的API
实质:浏览器上的hash表
缺点:占内存。(cookie不占内存)存在C盘的某文件里
1.LocalStorage和HTTP无关
2.HTTP不会带上localStorage的值
3.只有向同域名的页面才能互相读取LocalStorage(没有同源那么严格)
4.每个域名localStorage最大存储量为5MB左右(每个浏览器不同)
5.常用场景:记录有没有提示过用户(没用的信息,不可记录密码)
5.localStorage永久有效,除非用户清理浏览器缓存


image.png

SessionStorage(回话存储)
1234同上,API使用也一样
5.SessionStorage在用户关闭页面后就失效。

存值

localStorage.setItem('key','value') //自动转换成string类型
({}).toString //[object object]
localStorage.setIem('jsonString', JSON.stringify({name:'obj'})) //存对象

取值

localStorage.getItem(key'')

清除

localStorage.clear

面试题

1.cookie和session什么关系
答:session是基于、依赖于cookie实现的,cookie是基石

2.cookie和localStorage的区别?
答:localStorage不会被带入服务器,于http无关;最大存储量不同,4k、5Mb

3.sessionStorage和localStorage的区别
答:1.SessionStorage于session无关
2.SessionStorage在用户关闭页面(回话结束)后就失效

可以做到不基于cookie的session
前端不要读写cookie

相关文章

网友评论

      本文标题:Cookie,Session,localStorage

      本文链接:https://www.haomeiwen.com/subject/vvfzvqtx.html