实现cookie登录, 第一次登录成功后, cookie由服务端设置并保存在客户端, 后续访问在cookie过期前 (过期时间由后端设置) 将不需要登录 cookie出现的背景是 HTTP是无连接的,无状态的, 半双工(http2.0以下), 所以需要一个媒介存在http中, 服务端可以操作, 客户端也可以操作 就出现了cookie 纯后端实现cookie登录验证功能 node 后端
const fs = require ( 'fs' ) ;
const url = require ( 'url' ) ;
const http = require ( 'http' ) ;
const querystring = require ( 'querystring' ) ;
const path = require ( 'path' ) ; const server = http. createServer ( ( req, res ) => { let cookie = req. headers. cookie; cookie = cookie. replace ( / \s / g , '' ) ; const cookieInfo = querystring. parse ( cookie, ';' ) ; console. log ( cookie, cookieInfo) ; res. writeHead ( 200 , { 'content-type' : 'text/html' } ) ; if ( req. method. toUpperCase ( ) === 'GET' ) { if ( cookieInfo. token === 'abc' ) { fs. readFile ( './content.html' , ( err, data ) => { if ( err) { throw err; } res. end ( data, 'utf-8' ) ; } ) ; } else { fs. readFile ( './login.html' , ( err, data ) => { if ( err) { throw err; } res. end ( data, 'utf-8' ) ; } ) ; } } else { req. on ( 'data' , chunk => { let data = querystring. parse ( chunk. toString ( 'utf-8' ) ) ; if ( data. user === 'zhang' && data. pw === '123' ) { let date = new Date ( ) ; date. setDate ( date. getDate ( ) + 1 ) ; let expires = date. toUTCString ( ) ; res. writeHead ( 200 , { 'content-type' : 'text/html' , 'set-cookie' : [ ` token=abc; Expires= ${ expires} ; HttpOnly; ` , 'koken2=123' ] } ) ; fs. readFile ( './content.html' , ( err, data ) => { if ( err) { throw err; } res. end ( data, 'utf-8' ) ; } ) ; } else { fs. readFile ( './login.html' , ( err, data ) => { if ( err) { throw err; } res. end ( data, 'utf-8' ) ; } ) ; } } ) ; }
} ) ;
server. listen ( 3006 ) ;
未登录则返回登录页面
<! DOCTYPE html >
< html lang = " en" > < head> < meta charset = " UTF-8" /> < meta name = " viewport" content = " width=device-width, initial-scale=1.0" /> < title> 登录页</ title> </ head> < body> < h1> 请登录:</ h1> < form action = " http://127.0.0.1:3006/login" method = " post" enctype = " application/x-www-form-urlencoded" > < input name = " user" type = " text" /> < input name = " pw" type = " password" /> < input type = " submit" value = " 登录" /> </ form> </ body>
</ html>
已登录或有cookie凭证则返回内容页
<! DOCTYPE html >
< html lang = " en" > < head> < meta charset = " UTF-8" /> < meta name = " viewport" content = " width=device-width, initial-scale=1.0" /> < title> 内容页</ title> </ head> < body> < h1> 欢迎您~</ h1> </ body>
</ html>
实现比较简单, 仅是基础流程演示