/*
Koa 的中间件,无论写在前面还是后面,都会先执行中间件的代码,
*/
/*
Koa 路由 get 传值
在 Koa2 中 GET 传值通过request接收,但是接收的方法有两种: query 和 querystring
query : 返回的是格式化好的参数对象
querystring : 返回的是请求字符串
*/
// 引入模块
const Koa = require("koa");
const router = require("koa-router")(); //引入和实例化路由
// 实例化
var app = new Koa();
// Koa 中间件
/* 以下中间件中,有两个参数,路由地址和函数 ,没有路由只写函数的话,表示 匹配任何路由 ;
如果没有 next ,路由终止, 参数且执行next()函数,则无法向下继续执行;
如果不写 next , 这个路由被匹配到了之后就不会继续向下匹配。
*/
// app.use(async (ctx) => {
// console.log(new Date()); //返回当前日期时间 2021-01-21T16:31:36.278Z
// });
// 配置路由,ctx (上下万 context) 整合了 response 和 reject
router
.get("/", async (ctx) => {
ctx.body = "hi 首页123"; //返回数据 相当于 res.writeHead() res.end()
})
.get("/news", async (ctx, next) => {
// 与先的路由相同,也可以写成两个,
console.log("这是路由中间件1");
ctx.body = "这是新闻页面1";
await next(); //这里使用了 await next() ,将会继续向下匹配符合条件的路由,所以 ctx.body 浏览器页面出现的是新闻页面2
})
.get("/news", async (ctx) => {
console.log("页面2");
ctx.body = "这是新闻页面2";
});
// 也可以如下写法
router.get("/newscontent", async (ctx) => {
ctx.body = "新闻详情页面";
});
//
/*
Koa 的中间件,无论写在路由前面还是后面,都会先执行中间件的代码,
相比 Express, Express 是匹配到相应的路由后就不继续向下匹配了。
*/
app.use(async (ctx, next) => {
console.log(new Date()); //返回当前日期时间 2021-01-21T16:31:36.278Z
await next(); //当前路由匹配完成后继续向下匹配,查找相对于的路由去执行,找不找得到对应路由都会继续往下执行该中间件中的代码。
// 404 错误处理中间件
if (ctx.status === 404) {
ctx.status = 404;
ctx.body = "这是404页面";
} else {
console.log(ctx.url);
}
});
/*
//作用:启动路由
app.use(router.routes())
//作用:这是官方推荐的用法,建议使用
//我们可以看到 router.allowedMethods() 用在了路由匹配 router.routes() 之后,
//所以在当所有路由中间件最后调用,此时根据 ctx.status 设置 response 响应头
app.use(router.allowedMethods())
app.use(router.allowOrgins()) //跨域使用
*/
app.use(router.routes()).use(router.allowedMethods());
app.listen(3002);
console.log("http://localhost:3002");