Skip to content

Instantly share code, notes, and snippets.

@ryanlid
Created August 13, 2019 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanlid/6c3c85224ae8c321c3728ac5d44e6890 to your computer and use it in GitHub Desktop.
Save ryanlid/6c3c85224ae8c321c3728ac5d44e6890 to your computer and use it in GitHub Desktop.
koa 常用中间件
const koa = require("koa");
const views = require("koa-views");
const path = require("path");
const bodyParser = require("koa-bodyparser");
const static = require("koa-static");
const Router = require("koa-router");
const app = new koa();
const router = new Router();
// 加载模版引擎
app.use(views(__dirname + "/views"), {
map: { html: "ejs" }
});
// 加载静态资源
app.use(static(path.join(__dirname, "/static")));
// 渲染模版
router.get("/", async (ctx, next) => {
await ctx.render("index");
});
router.post("/", (ctx, next) => {
let postData = ctx.request.body;
ctx.body = postData;
});
app
.use(bodyParser())
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000);
@ryanlid
Copy link
Author

ryanlid commented Aug 13, 2019

npm i koa
npm i koa-bodyparser
npm i koa-router
npm i koa-views 
npm i koa-static

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment