2019-08-15 node各种小知识

2019-08-15  本文已影响0人  DreamNeverDie

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)     
上一篇下一篇

猜你喜欢

热点阅读