Created
August 14, 2019 08:44
-
-
Save ryanlid/3bf1a4b9a4116a2bffd98f45c1c4e692 to your computer and use it in GitHub Desktop.
koa-router 基本使用
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
}); |
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
如果把 get() 方法中
await next()
去掉,就不会命中 all() 方法的路由规则因为路由的处理也是一种中间件,如果不执行
await next()
而把控制权交给下一个中间件,那么后面的路由就不会再执行了。