Node.js系列学习之koa框架

news/2024/7/19 15:04:58 标签: js, javascript

系列文章目录

一阶段
1.Node基本模块之 fs
2. Node基本模块之stream
3.Node基本模块之http
4.Node基本模块之crypto
二阶段 koa框架
1.koa入门以及koal
2.koa的模板引擎Nunjucks
3.koa实现MVC模式
三阶段
1.Node+WebSocket 实现一个聊天室
四阶段
1.在koa中如何使用REST
2.在koa中编写符合REST 的接口


文章目录

  • 系列文章目录
  • 前言
  • 一、.koa是什么?
  • 二、middleware
  • 三、koa-router
  • 总结


前言

一、.koa是什么?

  • koa是Express的下一代基于Node.js的web框架,目前有1.x和2.0两个版本,我们这里学习的是2.0版本,其实1.x和2.0最大的区别就是实现异步的方式,koa 1.0使用generator实现异步,2.0则是使用promis结合async await 实现异步。

二、middleware

  1. 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示。
  2. 创建服务
  3. 监听端口

代码如下(示例):

javascript">const Koa = require('koa');
const app = new Koa();
app.use(async(ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = '<h1>Hello, koa2!</h1>';
});
app.listen(3000);
console.log('app started at port 3000...');

koa的核心执行逻辑分析:

javascript">app.use(async(ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = '<h1>Hello, koa2!</h1>';
});
  • 每收到一个http请求,koa就会调用通过app.use()注册的async函数,并传入ctx和next参数。我们可以对ctx进行操作,来设置response返回的内容。
  • await next()的作用是:koa把很多async函数组成一个处理链,每个async函数都可以做一些自己的事情,然后用await next()来调用下一个async函数。我们把每个async函数称为middleware,这些middleware可以组合起来,完成很多有用的功能
  • middleware的顺序很重要,也就是调用app.use()的顺序决定了middleware的顺序。
  • 如果一个middleware没有调用await next(),后续的middleware将不再执行了

我们可以创建多个middleware,如下:

javascript">app.use(async(ctx, next) => {
    console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL
    console.log('第一个middleware')
    await next(); // 调用下一个middleware

});

app.use(async(ctx, next) => {
    const start = new Date().getTime(); // 当前时间
    await next(); // 调用下一个middleware
    const ms = new Date().getTime() - start; // 耗费时间
    console.log(`Time: ${ms}ms`); // 打印耗费时间
    console.log('第二个middleware')
});

app.use(async(ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = '<h1>Hello, koa2!</h1>';
    console.log('第三个middleware')
});

三、koa-router

koa-router作用:

  • 为了处理不同的url,我们需要引入koa-router,koa-router可以处理不同url的映射,我们需要安装koa-router。

koa-router使用方法:

  • 1.npm install middleware --save
  • 2.引入 const router = require(‘koa-router’)();
  • 3.使用 app.use(router.routes());
javascript">const Koa = require('koa');
// 注意require('koa-router')返回的是函数:
const router = require('koa-router')();
router.get('/', async(ctx, next) => {
    ctx.response.body = '<h1>Index</h1>';
});
router.get('/home', async(ctx, next) => {
    ctx.response.body = '<h1>这是首页</h1>';
});
router.get('/pages', async(ctx, next) => {
    ctx.response.body = '<h1>这是其他页面</h1>';
});
//使用
app.use(router.routes());
app.listen(3000);

koa-router 对post请求的支持:

  • post请求通常会发送一个表单,或者JSON,它作为request的body发送,但无论是Node.js提供的原始request对象,还是koa提供的request对象
  • npm install koa-bodyparser --save
javascript">//引入
const bodyParser = require('koa-bodyparser');

router.post('/signin', async(ctx, next) => {
    var
        name = ctx.request.body.name || '',
        password = ctx.request.body.password || '';
    console.log(`signin with name: ${name}, password: ${password}`);
    if (name === 'koa' && password === '12345') {
        ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
    } else {
        ctx.response.body = `<h1>Login failed!</h1>
    <p><a href="/">Try again</a></p>`;
    }
});
//使用
app.use(bodyParser());

总结

这篇文章主要学习koa框架一些基础的知识点,简单的koa服务创建,以及利用koa-router映射地址,根据不同的path返回不同的数据。


http://www.niftyadmin.cn/n/1318917.html

相关文章

Vue中在mounted中通过this.$refs但是获取不到属性的几种常见情况分析

文章目录前言一、使用this.$refs 获取的组件使用了组件懒加载二、和Vue指令同用比如&#xff08;v-for&#xff0c;v-if&#xff0c;v-show等&#xff09;三、调用时机不对总结前言 Vue中在mounted中通过this.$refs但是获取不到属性的几种常见情况分析。 一、使用this.$refs 获…

hdu 3336 KMP

Count the string 1 /*2 写于13年3月21日3 http://acm.hdu.edu.cn/showproblem.php?pid33364 2013-03-21 10:39:01 Accepted 3336 46MS 2016K5 很巧妙的利用了KMP函数get_next()的思想6 通过对其进行改写达到目的7 data[i]表示[1....i]字符串出现的次数8 */9 10 …

Vue3.0中emit的使用

文章目录一、emit是什么&#xff1f;二、Vue 2.0和3.0的使用区别一、emit是什么&#xff1f; emit的主要作用是子组件可以通过使用 emit,让父组件监听到自定义事件 &#xff0c;以及传递的参数 二、Vue 2.0和3.0的使用区别 Vue 2.0&#xff1a; 子组件&#xff1a; methods…

angularJS disabled用法实例

angularJS disabled用法实例 angularJS此实例的覆盖知识点有&#xff1a; 1.ng-repeat的用法 2.filter的用法 3.页面显示时code转名称 4.ng-disabled在实例中的应用 5.angular.copy的应用 index2.html <!doctype html> <html ng-app><head><script src&qu…

Vite打包项目提示“some chunks are larger than 500 kib....“

在使用ViteVue3.0 打包过程中一直提示部分chunks过大。 解决办法&#xff0c;在vite.config.ts 中加入如下代码片段&#xff0c;重新打包提示消失。 build: {chunkSizeWarningLimit: 1000,rollupOptions: {output: {// 分包manualChunks(id) {if (id.includes("node_modu…

javascript学习笔记(3)--closest()和parents的区别

.closest().parents()从当前元素开始从父元素开始沿 DOM 树向上遍历&#xff0c;直到找到已应用选择器的一个匹配为止。沿 DOM 树向上遍历&#xff0c;直到文档的根元素为止&#xff0c;将每个祖先元素添加到一个临时的集合&#xff1b;如果应用了选择器&#xff0c;则会基于该…

ajax长轮询实例

html页面&#xff1a; <script> $(function(){ function test(){ $url"xx.php"; comet$.post($url,function(data){ if(datanull){ comet.abort…

Oracle 9i建表时需要加上MONITORING参数的作用

MONITORING参数说明&#xff1a;创建表时设置MONITORING参数, 使得Oracle跟踪对表的DML操作&#xff0c;预估DML操作所影响的记录数量。在Oracle 9i中, MONITORING参数不是默认的,需要手工执行,而在Oracle 10g及以上版本中, 该参数为默认设置。 1.创建表时设置MONITORING参数 c…