1.app.js
/**
* cookie的简介:
* 1、cookie保存在浏览器客户端
* 2、可以让我们用同一个浏览器访问同一个域名的时候共享数据
*
* cookie的作用:
* 1、保存用户信息
* 2、浏览器历史记录
* 3、猜你喜欢的功能
* 4、10天免登录
* 5、多个页面之间的数据传递
* 6、cookie实现购物车功能
*/
// 引入模块
const Koa = require('koa');
const router = require('koa-router')(); /*引入是实例化路由 推荐*/
const render = require('koa-art-template');
const path = require('path');
// 实例化
let app = new Koa();
// 配置 koa-art-template 模板引擎
render(app, {
root: path.join(__dirname, 'views'), // 视图的位置
extname: '.html', // 后缀名
debug: process.env.NODE_ENV !== 'production' // 是否开启调试模式
})
router.get('/', async (ctx) => {
// 正常就这样配置就可以了
/**
ctx.cookies.set('userinfo', 'zhangsan', {
maxAge: 1000 * 60 * 60
});
*/
ctx.cookies.set('userinfo', 'zhangsan11', {
maxAge: 1000 * 60 * 60,
// path: '/news', /*配置可以访问的页面*/
// domain: '.baidu.com', /*正常情况不要设置 默认就是当前域下面的所有页面都可以访问*/
/**
* a.baidu.com
* b.baidu.com 共享cookie
*/
httpOnly: false, // true表示这个cookie只有服务器端可以访问,false表示客户端(js)、服务器端都可以访问
})
let list = {
name: '张三'
}
await ctx.render('index', {
list: list
})
})
router.get('/news', async (ctx) => {
let userinfo = ctx.cookies.get('userinfo');
let app = {
name: '张三'
}
await ctx.render('news', {
list: app
});
})
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
2.views/index.html
<!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>
<link rel="stylesheet" href="css/basic.css" />
<script>
console.log(document.cookie);
</script>
</head>
<body>
<h2 class="title">这是一个koa-art-template</h2>
<h2>绑定数据</h2>
<%=list.name%>
</body>
</html>
views/news.html
<!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>
<link rel="stylesheet" href="css/basic.css" />
<script>
console.log(document.cookie);
</script>
</head>
<body>
<h2 class="title">这是一个koa-art-template</h2>
<h2>绑定数据</h2>
{{list.name}}
</body>
</html>
.