koa2入门——使用cookie
koa2 中操作的cookies是使用了npm的cookies模块,提供了从上下文直接读取、写入cookie的方法:
ctx.cookies.get(name, [options]) 读取上下文请求中的cookie
ctx.cookies.set(name, value, [options]) 在上下文中写入cookie
const router = require('koa-router')();
const request = require('co-request');
const jwt = require('jsonwebtoken');
const jwtKoa = require('koa-jwt')
const util = require('util')
const verify = util.promisify(jwt.verify);
const configUtil = require('../util/configUtil')
const serverConfig = configUtil.loadConfig();
router.all('/api/*', async (ctx, next) => {
let mapi = `${serverConfig.servicePath}${ctx.originalUrl}`;
let bodyString = JSON.stringify(ctx.request.body)
var opt = {
uri: mapi,
method: ctx.method,
headers: ctx.headers,
body: bodyString
};
let result = await request(opt);
let setcookie = result.headers["set-cookie"];
// Koa2 提供了从上下文中直接读取和写入 cookie 的方法 ctx.cookies.get(name, [options]) 和 ctx.cookies.set(name, value, [options])
let v = '';
if (setcookie) {
setcookie.forEach(
function (cookiestr) {
}
);
}
ctx.status = result.statusCode;
ctx.body = result.body;
});
##另一个
const Koa = require('koa')
const app = new Koa()
app.use( async ( ctx ) => {
if ( ctx.url === '/index' ) {
ctx.cookies.set(
'cid',
'hello world',
{
domain: 'localhost', // 写cookie所在的域名
path: '/index', // 写cookie所在的路径
maxAge: 10 * 60 * 1000, // cookie有效时长
expires: new Date('2017-02-15'), // cookie失效时间
httpOnly: false, // 是否只用于http请求中获取
overwrite: false // 是否允许重写
}
)
ctx.body = 'cookie is ok'
} else {
ctx.body = 'hello world'
}
})
app.listen(3000, () => {
console.log('[demo] cookie is starting at port 3000')
})