安装依赖
$ npm init ./treasure
$ cd treasure
$ npm i -S koa
$ npm i -S koa-router
$ npm i -S koa-static-cache
$ npm i -S koa-bodyparser
$ npm i -S koa-session
$ npm i -S art-template
$ npm i -S koa-art-template
$ npm i -S path
依赖组件
$ cat package.json
{
"name": "treasure",
"version": "0.0.1",
"private": false,
"dependencies": {
"art-template": "^4.13.2",
"koa": "^2.11.0",
"koa-art-template": "^1.1.1",
"koa-bodyparser": "^4.2.1",
"koa-router": "^7.4.0",
"koa-session": "^5.12.3",
"koa-static-cache": "^5.1.2",
"path": "^0.12.7"
}
}
项目结构
文件 | 描述 |
---|---|
config | 配置文件夹,配置文件使用JSON格式,配置内容根据运行环境分为development和production。 |
public | 静态资源文件存放目录 |
view | 视图模板文件存放目录 |
controller | 控制器文件存放目录 |
app.js | 应用启动文件 |
route.js | 路由配置文件 |
应用入口
$ vim app.js
const Koa = require("koa");
const bodyParser = require("koa-bodyparser");
const staticCache = require("koa-static-cache");
const session = require("koa-session");
const render = require("koa-art-template");
const {join} = require("path");
//创建应用
const app = new Koa();
//获取环境变量
const env = app.env || "development";
const debug = env === "development";
//路径设置
const basePath = join(__dirname, "public");
const configPath = join(__dirname, "config");
const viewPath = join(__dirname, "view");
const controllerPath = join(__dirname, "controller");
//应用配置
const appConfig = require(join(configPath, "app"))[env];
//会话配置
const sessionConfig = require(join(configPath, "session"))[env];
app.use(session(sessionConfig, app));
//使用静态文件解析器
app.use(staticCache(basePath));
//使用body解析器
app.use(bodyParser());
//使用模板引擎中间件
render(app, {root:viewPath, extname:".html", debug:debug});
//应用上下文设置属性
app.context.controllerPath = controllerPath;
//路由配置
require("./route")(app);
//监听端口 开启服务
app.listen(appConfig.port, _=>{
console.log("web server is starting");
});
配置文件
应用配置
$ vim config/app.json
{
"development": {
"port": 3001
},
"production": {
"port": 3001
}
}
会话配置
$ config/session.json
{
"development": {
"key": "session_key",
"maxAge": 604800000,
"overwrite": true,
"httpOnly": true,
"signed": true,
"rolling": true,
"renew": false
},
"production": {
"key": "session_key",
"maxAge": 604800000,
"overwrite": true,
"httpOnly": true,
"signed": true,
"rolling": true,
"renew": false
}
}
路由配置
$ route.js
const router = require("koa-router")();
const path = require("path");
module.exports = app=>{
//获取控制器路径
const controllerPath = app.context.controllerPath;
//加载控制器
const IndexController = require(path.join(controllerPath, "index"));
//路由规则
router.get("/", IndexController.index);
//应用使用路由中间件
app.use(router.routes()).use(router.allowedMethods());
};
控制器
$ controller/index.js
exports.index = async (ctx, next)=>{
console.log(ctx.controllerPath);
const title = "homepage";
const content = "hello world";
await ctx.render("index", {title, content});
};
视图
$ vim view/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
</head>
<body>
{{content}}
</body>
</html>