1. cookie是什么 #

2. Cookie的处理流程 #

3. 使用步骤 #

3.1 服务器发送cookie #

客户端第一次访问服务器的时候服务器通过响应头向客户端发送Cookie,属性之间用分号空格分隔

Set-Cookie:name=zhufeng; Path=/

3.2 客户端接收保存cookie #

客户端接收到Cookie之后保存在本地

3.3 客户端发送cookie #

以后客户端再请求服务器的时候会把此Cookie发送到服务器端

Cookie:name=zhufeng

4. cookie重要属性 #

5. koa中读写cookie #

5.1 server.js #

const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const router = new Router();
const Cookies = require('./cookies');
app.keys = ['zhufeng'];
app.use(async function (ctx, next) {
  ctx.cookies = new Cookies(ctx.req, ctx.res, { keys: app.keys });
  await next();
});
router.get('/write', async (ctx) => {
  //1.普通设置
  ctx.cookies.set('name', 'name_value');
  //2.设置过期时间
  ctx.cookies.set('name_expire', 'name_expire_value', {
    maxAge: 10 * 1000
  });
  //3.设置域名
  ctx.cookies.set('name_domain', 'name_domain_value', {
    domain: 'localhost'
  });
  //4.设置路径
  ctx.cookies.set('name_path', 'name_path_value', {
    path: '/read'
  });
  //5.设置httpOnly
  ctx.cookies.set('name_httpOnly', 'name_httpOnly_value', {
    httpOnly: true
  });
  ctx.body = '发送Cookie给客户端';
});
router.get('/read', async (ctx) => {
  const name = ctx.cookies.get('name');
  const name_expire = ctx.cookies.get('name_expire');
  const name_domain = ctx.cookies.get('name_domain');
  const name_path = ctx.cookies.get('name_path');
  const name_httpOnly = ctx.cookies.get('name_httpOnly');
  let values = [name, name_expire, name_domain, name_path, name_httpOnly]
  //2.获取客户端发送过来的Cookie
  ctx.body = values.join(',');
});
app.use(router.routes());
app.listen(3000, () => {
  console.log('Server is running at http://localhost:3000');
});

5.2 cookie.js #


function Cookies(req,res){
    this.req = req;
    this.res  = res;
}

Cookies.prototype.set = function(name,value,attrs){
    const headers = this.res.getHeader('Set-Cookie')||[];
    let cookie = new Cookie(name,value,attrs);
    headers.push(cookie.toHeader());
    this.res.setHeader('Set-Cookie',headers);
}
Cookies.prototype.get = function(name){
    let cookie = this.req.headers.cookie||'';
    return getValueFromHeader(name,cookie);
}
function getValueFromHeader(name,cookie){
    if(!cookie) return ;
    let regexp = new RegExp("(?:^|;) *"+name+"=([^;]*)");
    let match = cookie.match(regexp);
    if(match){
        return match[1];
    }
}
function Cookie(name,value,attrs){
    this.name = name;
    this.value = value;
    for(let name in attrs){
        this[name]=attrs[name];
    }
}
Cookie.prototype.toString = function(){
    return  this.name +'='+this.value;
}
Cookie.prototype.toHeader = function(){
    let header = this.toString();
    if(this.path) header += `; path=`+this.path;
    if (this.maxAge) this.expires = new Date(Date.now() + this.maxAge);
    if(this.expires) header += `; expires=`+this.expires.toUTCString();
    if(this.domain) header += `; domain=`+this.domain;
    if(this.httpOnly) header += `; httpOnly`;
    console.log(header);
    return header;
}
module.exports = Cookies

6. 登录 #

const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const router = new Router();
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
router.get('/login', async ctx => {
  ctx.body = `
    <form action="/login" method="post">
      <input type="text" name="username" />
      <input type="submit" value="提交" />
    </form>
  `;
});
router.post('/login', async ctx => {
  ctx.cookies.set('username', ctx.request.body.username);
  ctx.redirect('/user');
});
router.get('/user', async ctx => {
  if (ctx.cookies && ctx.cookies.get('username')) {
    ctx.body = ctx.cookies.get('username');
  } else {
    return ctx.redirect('/login');
  }
});
app.use(router.routes());
app.listen(8080, () => {
  console.log('Server is running at http://localhost:8080');
});

7.cookie使用注意事项 #

8.sign #

const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const router = new Router();
app.keys = ['zhufeng'];
router.get('/write', async (ctx) => {
    ctx.cookies.set('username', 'zhangsan', {
        signed: true 
    });
    ctx.body = 'write ok';
});
router.get('/read', async (ctx) => {
    const username = ctx.cookies.get('username', {
        signed: true 
    });
    ctx.body = "username:"+username;
});
app.use(router.routes());
app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});