KoaJS教程

Koa.js 路由

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 = koa();
var _ = router();              //Instantiate the router
_.get('/hello', getMessage);   // Define routes
function *getMessage() {
   this.body = "Hello world!";
};
app.use(_.routes());           //Use the routes defined using the router
app.listen(3000);
如果我们运行我们的应用程序并转到 localhost:3000/hello,服务器会在路由"/hello"处收到一个 get 请求。我们的 Koa 应用程序执行附加到此路由的回调函数并发送"Hello World!"作为回应。
Routing Hello
我们也可以在同一路线上有多种不同的方法。例如,
var koa = require('koa');
var router = require('koa-router');
var app = koa();
var _ = router(); //Instantiate the router
_.get('/hello', getMessage);
_.post('/hello', postMessage);
function *getMessage() {
	this.body = "Hello world!";
};
function *postMessage() {
   this.body = "You just called the post method at '/hello'!\n";
};
app.use(_.routes()); //Use the routes defined using the router
app.listen(3000);
要测试此请求,请打开终端并使用 cURL 执行以下请求
curl-X POST "https://localhost:3000/hello"
Curl Routing
express 提供了一种特殊的方法 all,可以使用相同的函数处理特定路由上的所有类型的 http 方法。要使用此方法,请尝试以下操作-
_.all('/test', allMessage);
function *allMessage(){
   this.body = "All HTTP calls regardless of the verb will get this response";
};
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4