There is no need to import other modules to handle cookies in Koa, as long as you get the CTX object, you can manipulate cookies

Demopark.github. IO /koa-docs- en…

Waste don’t say much, go straight to the code

const Koa = require("koa"); const Router = require("koa-router"); const app = new Koa(); const router = new Router(); const bodyParser = require("koa-bodyparser"); app.use(bodyParser()); Router.get ("/setCookie", (CTX, next) => {/* First parameter: set the key of the cookie second parameter: set the value of the cookie third parameter: Set ("name", "sandy", {path: "/", // valid range httpOnly: true, // maxAge can only be modified on the server: 24 * 60 * 60 * 1000,}); }); router.get("/getCookie", (ctx, next) => { console.log(ctx.cookies.get("name")); }); app.use(router.routes()).use(router.allowedMethods()); app.listen(999);Copy the code

rendering

Cookies in Koa cannot be set in Chinese by default

But if you still want to set a Chinese cookie there is a way

const Koa = require("koa"); const Router = require("koa-router"); const app = new Koa(); const router = new Router(); const bodyParser = require("koa-bodyparser"); app.use(bodyParser()); Router. Get ("/setCookie", (CTX, next) => {let value = new Buffer(" sandy ").toString("base64"); ctx.cookies.set("userName", value, { path: "/", httpOnly: true, maxAge: 24 * 60 * 60 * 1000, }); }); router.get("/getCookie", (ctx, next) => { let value = ctx.cookies.get("userName"); let res = new Buffer(value, "base64").toString(); console.log(res); }); app.use(router.routes()).use(router.allowedMethods()); app.listen(999);Copy the code

rendering