http://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001434501628911140e1cb6ce7d42e5af81480f7ecd5802000
package.json
{
"name": "view-koa",
"version": "1.0.0",
"description": "koa 2 example with nunjucks as view",
"main": "app.js",
"scripts": {
"start": "node --use_strict app.js"
},
"keywords": [
"koa",
"async",
"nunjucks"
],
"author": "Michael Liao",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/michaelliao/learn-javascript.git"
},
"dependencies": {
"koa": "2.0.0",
"koa-bodyparser": "3.2.0",
"koa-router": "7.0.0",
"nunjucks": "2.4.2",
"mime": "1.3.4",
"mz": "2.4.0"
}
}
views
base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="description" content="learn javascript by www.liaoxuefeng.com">
<title>{{ title }}</title>
<link rel="stylesheet" href="/static/css/bootstrap.css">
<script src="/static/js/bootstrap.js"></script>
</head>
<body>
<header class="navbar navbar-static-top">
<div class="container">
<div class="navbar-header">
<a href="/" class="navbar-brand">Learn JavaScript</a>
</div>
<nav class="collapse navbar-collapse" id="bs-navbar">
<ul class="nav navbar-nav">
<li><a target="_blank" href="http://www.liaoxuefeng.com/">Get Courses</a></li>
<li><a target="_blank" href="https://github.com/michaelliao/learn-javascript">Source Code</a></li>
<li><a target="_blank" href="http://getbootstrap.com/">Resource</a></li>
</ul>
</nav>
</div>
</header>
<div id="important" style="color:#cdbfe3; background-color:#6f5499; padding:30px 0; margin:-20px 0 20px 0;">
<div class="container">
<h1 style="color:#fff; font-size:60px">Getting started</h1>
<p style="font-size:24px; line-height:48px">Learn JavaScript, Node.js, npm, koa2, nunjucks, babel, etc. at liaoxuefeng.com.</p>
</div>
</div>
{% block main %} {% endblock %}
<footer style="background-color:#ddd; padding: 20px 0;">
<div class="container">
<p>
<a target="_blank" href="http://www.liaoxuefeng.com">Website</a> -
<a target="_blank" href="https://github.com/michaelliao/learn-javascript">GitHub</a> -
<a target="_blank" href="http://weibo.com/liaoxuefeng">Weibo</a>
</p>
<p>This JavaScript course is created by <a target="_blank" href="http://weibo.com/liaoxuefeng">@廖雪峰</a>.</p>
<p>Code licensed <a target="_blank" href="https://github.com/michaelliao/learn-javascript/blob/master/LICENSE">Apache</a>.</p>
</div>
</footer>
</body>
</html>
index.html
{% extends "base.html" %} {% block main %}
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><span class="glyphicon glyphicon-user"></span> Please sign in</h3>
</div>
<div class="panel-body">
<form action="/signin" method="post">
<div class="form-group">
<label>Email address</label>
<input type="email" name="email" class="form-control" placeholder="Email">
<p class="help-block">Use email: admin@example.com</p>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" placeholder="Password">
<p class="help-block">Use password: 123456</p>
</div>
<button type="submit" class="btn btn-primary">Sign In</button>
</form>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><span class="glyphicon glyphicon-hd-video"></span> Video training</h3>
</div>
<div class="panel-body">
<video width="100%" controls="controls">
<source src="https://github.com/michaelliao/learn-javascript/raw/master/video/vscode-nodejs.mp4">
</video>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h1>Get more courses...</h1>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">JavaScript</h3>
</div>
<div class="panel-body">
<p>full-stack JavaScript course</p>
<p><a target="_blank" href="http://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000">Read more</a></p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Python</h3>
</div>
<div class="panel-body">
<p>the latest Python course</p>
<p><a target="_blank" href="http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000">Read more</a></p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">git</h3>
</div>
<div class="panel-body">
<p>A course about git version control</p>
<p><a target="_blank" href="http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000">Read more</a></p>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
signin-ok.html
{% extends "base.html" %} {% block main %}
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Sign in successfully!</h1>
<div class="alert alert-success"> <strong>Well done!</strong> You successfully signed in as {{ name }}!
</div>
<p><a href="/">Back to home</a></p>
</div>
</div>
</div>
{% endblock %}
signin-failed.html
{% extends "base.html" %} {% block main %}
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Sign in failed!</h1>
<div class="alert alert-danger"> <strong>Sorry!</strong> Your email or password does not match! Please try again.
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><span class="glyphicon glyphicon-user"></span> Please sign in</h3>
</div>
<div class="panel-body">
<form action="/signin" method="post">
<div class="form-group">
<label>Email address</label>
<input type="email" name="email" class="form-control" placeholder="Email">
<p class="help-block">Use email: admin@example.com</p>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" placeholder="Password">
<p class="help-block">Use password: 123456</p>
</div>
<button type="submit" class="btn btn-primary">Sign In</button>
</form>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><span class="glyphicon glyphicon-hd-video"></span> Video training</h3>
</div>
<div class="panel-body">
<video width="100%" controls="controls">
<source src="https://github.com/michaelliao/learn-javascript/raw/master/video/vscode-nodejs.mp4">
</video>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
controllers
index.js
// index:
module.exports = {
'GET /': async (ctx, next) => {
ctx.render('index.html', {
title: 'Welcome'
});
}
};
signin.js
// sign in:
module.exports = {
'POST /signin': async (ctx, next) => {
var
email = ctx.request.body.email || '',
password = ctx.request.body.password || '';
if (email === 'admin@example.com' && password === '123456') {
console.log('signin ok!');
ctx.render('signin-ok.html', {
title: 'Sign In OK',
name: 'Mr Node'
});
} else {
console.log('signin failed!');
ctx.render('signin-failed.html', {
title: 'Sign In Failed'
});
}
}
};
/
static-files.js
const path = require('path');
const mime = require('mime');
const fs = require('mz/fs');
function staticFiles(url, dir) {
return async (ctx, next) => {
let rpath = ctx.request.path;
if (rpath.startsWith(url)) {
let fp = path.join(dir, rpath.substring(url.length));
if (await fs.exists(fp)) {
ctx.response.type = mime.lookup(rpath);
ctx.response.body = await fs.readFile(fp);
} else {
ctx.response.status = 404;
}
} else {
await next();
}
};
}
module.exports = staticFiles;
templating.js
const nunjucks = require('nunjucks');
function createEnv(path, opts) {
var
autoescape = opts.autoescape === undefined ? true : opts.autoescape,
noCache = opts.noCache || false,
watch = opts.watch || false,
throwOnUndefined = opts.throwOnUndefined || false,
env = new nunjucks.Environment(
new nunjucks.FileSystemLoader(path, {
noCache: noCache,
watch: watch,
}), {
autoescape: autoescape,
throwOnUndefined: throwOnUndefined
});
if (opts.filters) {
for (var f in opts.filters) {
env.addFilter(f, opts.filters[f]);
}
}
return env;
}
function templating(path, opts) {
var env = createEnv(path, opts);
return async (ctx, next) => {
ctx.render = function (view, model) {
ctx.response.body = env.render(view, Object.assign({}, ctx.state || {}, model || {}));
ctx.response.type = 'text/html';
};
await next();
};
}
module.exports = templating;
controller.js
const fs = require('fs');
// add url-route in /controllers:
function addMapping(router, mapping) {
for (var url in mapping) {
if (url.startsWith('GET ')) {
var path = url.substring(4);
router.get(path, mapping[url]);
console.log(`register URL mapping: GET ${path}`);
} else if (url.startsWith('POST ')) {
var path = url.substring(5);
router.post(path, mapping[url]);
console.log(`register URL mapping: POST ${path}`);
} else if (url.startsWith('PUT ')) {
var path = url.substring(4);
router.put(path, mapping[url]);
console.log(`register URL mapping: PUT ${path}`);
} else if (url.startsWith('DELETE ')) {
var path = url.substring(7);
router.del(path, mapping[url]);
console.log(`register URL mapping: DELETE ${path}`);
} else {
console.log(`invalid URL: ${url}`);
}
}
}
function addControllers(router, dir) {
fs.readdirSync(__dirname + '/' + dir).filter((f) => {
return f.endsWith('.js');
}).forEach((f) => {
console.log(`process controller: ${f}...`);
let mapping = require(__dirname + '/' + dir + '/' + f);
addMapping(router, mapping);
});
}
module.exports = function (dir) {
let
controllers_dir = dir || 'controllers',
router = require('koa-router')();
addControllers(router, controllers_dir);
return router.routes();
};
app.js
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const controller = require('./controller');
const templating = require('./templating');
const app = new Koa();
const isProduction = process.env.NODE_ENV === 'production';
// log request URL:
app.use(async (ctx, next) => {
console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
var
start = new Date().getTime(),
execTime;
await next();
execTime = new Date().getTime() - start;
ctx.response.set('X-Response-Time', `${execTime}ms`);
});
// static file support:
if (! isProduction) {
let staticFiles = require('./static-files');
app.use(staticFiles('/static/', __dirname + '/static'));
}
// parse request body:
app.use(bodyParser());
// add nunjucks as view:
app.use(templating('views', {
noCache: !isProduction,
watch: !isProduction
}));
// add controller:
app.use(controller());
app.listen(3000);
console.log('app started at port 3000...');