Skip to content

Instantly share code, notes, and snippets.

@ryanlid
Created August 14, 2019 08: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/3bf1a4b9a4116a2bffd98f45c1c4e692 to your computer and use it in GitHub Desktop.
Save ryanlid/3bf1a4b9a4116a2bffd98f45c1c4e692 to your computer and use it in GitHub Desktop.
koa-router 基本使用
const Koa = require("koa");
const Route = require("koa-router");
const app = new Koa();
const router = Route();
router
.get("/", async (ctx, next) => {
ctx.body = "Hello World";
console.log("get");
await next()
})
.all("/", async (ctx, next) => {
console.log("all");
await next()
});
app.use(router.routes());
app.listen(3000, () => {
console.log("Server is running at http://localhost:3000");
});
@ryanlid
Copy link
Author

ryanlid commented Aug 14, 2019

如果把 get() 方法中 await next() 去掉,就不会命中 all() 方法的路由规则

因为路由的处理也是一种中间件,如果不执行 await next() 而把控制权交给下一个中间件,那么后面的路由就不会再执行了。

@ryanlid
Copy link
Author

ryanlid commented Aug 14, 2019

all() 方法可以用来设置请求头

router.all("/*", async (ctx, next) => {
  // 符号* 代表允许来自所有域名的请求
  ctx.set("Access-Control-Allow-Origin", "https://www.example.com");
  await next();
});

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