2019-08-15 node各种小知识

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(`
    
        
            
            
            
            Document
        
        
        欢迎你第${session[sessionID].view}次访问本站
        
    `)
    res.end()

})

app.listen(3000)     

你可能感兴趣的:(2019-08-15 node各种小知识)