上海建站中心,夫妻网站开发,wordpress插件文档,上海前端实现cookie登录, 第一次登录成功后, cookie由服务端设置并保存在客户端, 后续访问在cookie过期前 (过期时间由后端设置) 将不需要登录cookie出现的背景是 HTTP是无连接的#xff0c;无状态的, 半双工(http2.0以下), 所以需要一个媒介存在http中, 服务端可以操作, 客户端也可以…实现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: [tokenabc; Expires${expires}; HttpOnly;, koken2123]});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 langenheadmeta charsetUTF-8 /meta nameviewport contentwidthdevice-width, initial-scale1.0 /title登录页/title/headbodyh1请登录:/h1form actionhttp://127.0.0.1:3006/login methodpost enctypeapplication/x-www-form-urlencodedinput nameuser typetext /input namepw typepassword /input typesubmit value登录 //form/body
/html已登录或有cookie凭证则返回内容页
!DOCTYPE html
html langenheadmeta charsetUTF-8 /meta nameviewport contentwidthdevice-width, initial-scale1.0 /title内容页/title/headbodyh1欢迎您~/h1/body
/html实现比较简单, 仅是基础流程演示