我正在尝试使用Koa.js,并检查了以下模块的路由请求: 1. koa-route 2. koa-mount
当我在google中查看他们的github页面/教程时,这些示例看起来几乎相似,只有细微差别。
对于koa-route:
var route = require('koa-route');
app.use(route.get('/', index));
//functions to handle the request
function* index(){
this.body = "this should be home page!";
}
对于koa-mount:
//syntax to add the route
var mount = require('koa-mount');
var a = koa();
app.use(mount('/hello', a));
//functions to handle the request
a.use(function *(next){
yield next;
this.body = 'Hello';
});
在我看来唯一的区别是mount需要一个中间件来提供请求,而route需要一个生成器来处理请求。
我很困惑何时使用什么以及什么时候使用它们(在某些教程中看到过)?
答案 0 :(得分:4)
Koa-mount的目的是将一个应用程序安装到另一个应用程序中。例如,您可以创建独立的博客应用程序并将其安装到另一个应用程序。您也可以安装其他人创建的应用程序。
答案 1 :(得分:0)
koa-mount-将不同的koa应用程序装入您的给定路由。
const mount = require('koa-mount');
const Koa = require('koa');
// hello
const Hello = new Koa();
Hello.use(async function (ctx, next){
await next();
ctx.body = 'Hello';
});
// world
const World = new Koa();
World.use(async function (ctx, next){
await next();
ctx.body = 'World';
});
// app
const app = new Koa();
app.use(mount('/hello', Hello));
app.use(mount('/world', World));
app.listen(3000);
console.log('listening on port 3000');
上面的示例具有三个不同的koa应用程序Hello,World和app。 app:3000 / hello路线安装koa应用程序Hello和app:3000 / world路线安装koa应用程序World。 Hello和World是安装在应用程序应用程序上的2个不同的独立koa应用程序。
Koa-route不适用于多个koa应用程序。它将仅处理一个应用程序。因此,Hello和World应该是应用程序中的类/方法。
const route = require('koa-route');
const Koa = require('koa');
const Hello = async (ctx, next) => {
await next();
ctx.body = "Hello"
}
const World = async (ctx, next) => {
await next();
ctx.body = "World"
}
// app
const app = new Koa();
app.use(mount('/hello', Hello));
app.use(mount('/world', World));
app.listen(3000);
console.log('listening on port 3000');
koa-route的另一件事可以处理将koa-mount用作中间件的中间件。