美文网首页
2019-08-15 node各种小知识

2019-08-15 node各种小知识

作者: DreamNeverDie | 来源:发表于2019-08-15 19:41 被阅读0次

    1.原生接收和设置cookie

    const http=require('http')
    
    let app=http.createServer(function(req,res){
        console.log(req.headers['cookie'])
        res.setHeader('set-cookie',"who=me")
        res.write('aaa')
        res.end();
    })
    
    app.listen(3000)     
    

    2.原生实现session

    const http = require('http')
    
    let session = {}
    let app = http.createServer(function (req, res) {
        if (req.url == '/favicon.ico') {
            res.end()
            return;
        }
    
        let sessionID='';
        if(req.headers['cookie']){
    
            req.headers['cookie'].split(';').forEach((item) => {
                let [name, value] = item.split('=');
                if (name = 'sessID')
                    sessionID = value;
            })
        }
    
        if (sessionID) {
            if (!session[sessionID]) {
    
                session[sessionID] = {}
            }
    
        } else {
            sessionID = Math.floor(Math.random() * 10000000000)
    
            res.setHeader('set-cookie', `sessID=${sessionID}`)
    
            session[sessionID] = {}
    
        }
    
        session[sessionID].view = session[sessionID].view || 0;
        session[sessionID].view++;
    
        res.write(`<!DOCTYPE html>
        <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <meta http-equiv="X-UA-Compatible" content="ie=edge">
                <title>Document</title>
            </head>
            <body>
            欢迎你第${session[sessionID].view}次访问本站
            </body>
        </html>`)
        res.end()
    
    })
    
    app.listen(3000)     
    

    相关文章

      网友评论

          本文标题:2019-08-15 node各种小知识

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