教程 > koa.js 中文教程 > 阅读:208

koa.js 路由——迹忆客-ag捕鱼王app官网

web 框架在不同的路由上提供诸如 html 页面、脚本、图像等资源。 koa 不支持核心模块中的路由。 我们需要使用 koa-router 模块在 koa 中创建路由。 使用以下命令安装此模块。

$ npm install --save koa-router

现在我们已经安装了 koa-router,让我们看一个简单的 get 路由示例。

var koa = require('koa');
var router = require('koa-router');
var app = new koa();
var _ = router();              // 实例化一个路由
_.get('/hello', getmessage);   // 定义路由
function getmessage(ctx,next) {
   ctx.body = "hello 迹忆客!";
};
app.use(_.routes());  
app.listen(3000);

如果我们运行我们的应用程序并访问 http://localhost:3000/hello ,服务器会在路由 “/hello” 处收到一个 get 请求。 我们的 koa 应用程序执行附加到该路由的回调函数并返回 “hello 迹忆客!” 作为回应。

koa 路由

我们也可以在同一条路由上有多种不同的方法。 例如,

var koa = require('koa');
var router = require('koa-router');
var app = koa();
var _ = router(); // 实例化一个路由
_.get('/hello', getmessage);
_.post('/hello', postmessage);
function getmessage(ctx,next) {
    ctx.body = "hello 迹忆客!";
};
function postmessage(ctx,next) {
   ctx.body = "您刚刚调用了 post 方法 '/hello'!\n";
};
app.use(_.routes()); // 注册使用路由器定义的路由
app.listen(3000);

要测试此请求,打开终端并使用 curl 执行以下请求

$ curl -x post "https://localhost:3000/hello"

koa post 请求

express 提供了一个特殊的方法 all 来使用相同的函数在特定路由处处理所有类型的 http 方法。 要使用此方法,尝试进行以下操作

_.all('/test', allmessage);
function *allmessage(){
   this.body = "无论动词如何,所有 http 调用都会得到这个响应";
};

查看笔记

扫码一下
查看教程更方便
网站地图