Cookie Session localStorage sessionStorage difference

cookie:

Since HTTP requests are stateless, we need to recognize that the request is identity, so we have cookies, which are used to identify identity; Browsers and servers can set cookies; Cookie do not set too large, may cause the page white screen, waste traffic, etc. (you can set cookies reasonably according to the path, periodically delete cookies); Cookies are ultimately stored on the client, so the biggest problem with cookies is that they are not secure.

session:

It is not safe for cookies to exist on the client. In order to solve the problem of cookie insecurity, session is born. Session is stored on the server, and session is realized based on cookies

localStorage:

Browser local storage, can store some network resources, closed the page, the next time can still use

sessionStorage:

Used to transfer values between pages and destroyed immediately after the page is closed

cookie

  • Name: key set by the user
  • Value: indicates the value set by the user
  • Domain: specifies the domain name. The default value is the current domain name
  • Path: Limits the path for setting cookies (rarely used) to reduce cookie incoming
  • MaxAge /Expires: Specifies the number of seconds after the maxAge Expires Expires
  • HttpOnly: set to true. Cookies cannot be modified by code, but can still be modified in browser cookies
/ / set the cookie
res.setHeader('Set-Cookie'['name=zs; max-age=10'.'age=18; httpOnly=true']);

/ / get a cookie
req.headers('cookie')
Copy the code

Change cookie Settings and modifications to simpler

It is more troublesome to use native Settings and obtain cookies in development. We prefer to set a cookie by setCookie and getCookie to obtain a cookie.

const http = require('http');
const querystring = require('querystring');

const server = http.createServer((req, res) = > {
    / / get a cookie
    req.getCookie = (key) = > {
        let cookieObj = querystring.parse(req.headers['cookie'].'; ');
        if (cookieObj && cookieObj[key]) {
            return cookieObj[key]
        } else {
            return ' '}}/ / set the cookie
    let cookies = [];
    res.setCookie = (key, value, options) = > {
        let optArgs = [];
        if (options.maxAge) {
            optArgs.push(`max-age=${options.maxAge}`)}if (options.httpOnly) {
            optArgs.push(`httpOnly=${options.httpOnly}`)}if (options.path) {
            optArgs.push(`path=${options.path}`)}if (options.domain) {
            optArgs.push(`domain=${options.domain}`)}if (options.Expires) {
            optArgs.push(`Expires=${options.Expires}`)}const cookieValue = `${key}=${value}`;
        cookies.push(`${cookieValue}; ${optArgs.join('; ')}`);
        console.log(cookies)
        res.setHeader('Set-Cookie', cookies)
    }

    if (req.url == '/read') {
        const value = req.getCookie('name');
        res.end(value);
    } else if (req.url === '/write') {
        res.setCookie('name'.'zs', {
            maxAge: 30
        });
        res.setCookie('age'.18, {
            httpOnly: true
        });
        res.end('write ok');
    } else {
        res.statusCode = 404;
        res.end('Not Found'); }}); server.listen(3000.() = > {
    console.log(`start sever success`)})Copy the code

Cookies with salt

const http = require('http');
const querystring = require('querystring');
const crypto = require('crypto');
// Salt value, the value here is just a simulation, normally we would produce a 1028 byte key through Opensll
const key = 'hh';
// Add salt to the value
function signed(value) {
    // We need to set value.tostring () in case the user sets it to a numeric type
    return crypto.createHmac('sha256', key).update(value.toString()).digest('base64');
}
const server = http.createServer((req, res) = > {
    / / get a cookie
    req.getCookie = (key, options = {}) = > {
        let cookieObj = querystring.parse(req.headers['cookie'].'; ');
        console.log(cookieObj)
        // Whether to verify the signature
        if (options.signed) {
            const [value, sign] = cookieObj[key].split('. ');
            return signed(value) == sign ? value : ' ';
        } else {
            return cookieObj && cookieObj[key] ? cookieObj[key].split('. ') [0] : ' '}}/ / set the cookie
    let cookies = [];
    res.setCookie = (key, value, options) = > {
        let optArgs = [];
        if (options.maxAge) {
            optArgs.push(`max-age=${options.maxAge}`)}if (options.httpOnly) {
            optArgs.push(`httpOnly=${options.httpOnly}`)}if (options.path) {
            optArgs.push(`path=${options.path}`)}if (options.domain) {
            optArgs.push(`domain=${options.domain}`)}if (options.Expires) {
            optArgs.push(`Expires=${options.Expires}`)}// Add salt to value
        if (options.signed) {
            value = `${value}.${signed(value)}`;
        }
        const cookieValue = `${key}=${value}`;
        cookies.push(`${cookieValue}; ${optArgs.join('; ')}`);
        res.setHeader('Set-Cookie', cookies)
    }

    if (req.url == '/read') {
        const value = req.getCookie('age', {
            signed: true
        });
        console.log(value)
        res.end(value);
    } else if (req.url === '/write') {
        res.setCookie('name'.'zs', {
            maxAge: 30
        });
        res.setCookie('age'.18, {
            httpOnly: true.signed: true
        });
        res.end('write ok');
    } else {
        res.statusCode = 404;
        res.end('Not Found'); }}); server.listen(3000.() = > {
    console.log(`start sever success`)})Copy the code

session

Cookies are put on the client, so it’s not secure, session is on the house server

const http = require('http');
const querystring = require('querystring');
const crypto = require('crypto');
const uuid = require('uuid');
const key = 'hh';
const CardName = 'connect.sid';
const session = {};

function signed(val) {
    return crypto.createHmac('sha256', key).update(val).digest('base64');
}
const server = http.createServer((req, res) = > {
    req.getCookie = function(key, options) {
        const cookie = req.headers['cookie'];
        const cookieObj = querystring.parse(cookie);
        if (options.signed) {
            let [value, sign] = cookieObj[key].split('. ');
            return signed(value) === sign ? value : ' ';
        } else {
            return cookieObj[key] ? cookieObj[key].split('. ') [0] : ' '; }}let cookies = [];
    res.setCookie = function(key, value, options) {
        let optArgs = [];
        if (options.MaxAge) {
            optArgs.push(`max-age=${options.MaxAge}`);
        }
        if (optArgs.path) {
            optArgs.push(`path=${optArgs.path}`);
        }
        if (optArgs.httpOnly) {
            optArgs.push(`httpOnly=${optArgs.httpOnly}`);
        }
        if (optArgs.domain) {
            optArgs.push(`domain=${optArgs.domain}`);
        }
        if (optArgs.Expires) {
            optArgs.push(`Expires=${optArgs.Expires}`);
        }
        const cookieVal = `${key}=${value}`;
        cookies.push(`${cookieVal}; ${optArgs.join('; ')}`);
        res.setHeader('Set-Cookie', cookies);
    }

    if (req.url === '/cut') {
        let cardId = rq.getCookie(CardName);
        // The session is cleared when the server restarts
        if (cardId && session[cardId]) {
            session[cardId].mmy = -10;
            res.end(`${session[cardId].mmy} money`);
        } else { // For the first time, you need to get a card
            const cardId = uuid.v4();
            session[cardId] = {
                mmy: 500
            };
            res.setCookie(CardName, cardId, {
                httpOnly: true}); }}else{ res.end(); }}); server.listen(3000.() = > {
    console.log('start sever success');
})
Copy the code