app.js
var Koa = require('koa')
var fs = require('fs')
var path = require('path')
var koaStaticPlus = require('koa-static-plus')
var Router = require('./router')
var app = new Koa()
//处理静态资源
app.use(koaStaticPlus(path.join(__dirname, '/dist'), {
pathPrefix: ''
}))
Router.get('/', function (a) {
a.body = "xxxx"
})
Router.get('/aaa', function (a) {
a.body = "aaaaaa"
})
app.use(function (ctx, next) {
console.log(ctx.method, ctx.url)
Router.match(ctx, next)
})
app.listen(4000, function () {
console.log('server started 4000')
})
module.exports = app
集中定义路由
现有的所有路由在koa2 都不好用,GITHUB上示例又少,自己实现一个简单的
var Router = {map: {}}
'get,del,put,post'.replace(/w+/g, function (a) {
var method = a.toUpperCase()
Router.map[method] = []
Router[a] = function (url, cb) {
var keys = []
var re = pathToRegexp(url, keys)
this.map[method].push({
re: re,
url: url,
cb: cb
})
}
})
var pathToRegexp = require('path-to-regexp')
Router.onerror = function (ctx) {
ctx.body = '404!!'
}
Router.match = function (ctx, next) {
var array = this.map[ctx.method] || []
for (var i = 0, el; el = array[i++]; ) {
var aaa = el.re.exec(ctx.url)
if (aaa) {
var args = aaa.slice(1)
el.cb(ctx, next, args)
return
}
}
Router.onerror(ctx, next)
}
module.exports = Router
//http://my.oschina.net/u/1416844/blog/660951
require("babel-core/register")(
{
presets: ['stage-3','es2015']
}
);
//http://stackoverflow.com/questions/31122193/babel-polyfill-what-is-that
require("babel-polyfill");
require("./app.js");
我们