Koa2 与它的中间件们

栏目: Node.js · 发布时间: 7年前

内容简介:ES6 的模块语法入口文件使用不嫌弃配置麻烦的话,也可以考虑

Node.js

reify

Enable ECMAScript 2015 modules in Node today. No caveats. Full stop.

ES6 的模块语法 import 在 node 环境中仍然不兼容,或者说需要 ejs 文件格式。

入口文件使用 reify 解决:

require("reify")

不嫌弃配置麻烦的话,也可以考虑 babel

中间件

Koa2 需要配合非常多中间件来使用,才能成为一个后端框架。

koa-conditional-get

Conditional Get 又名 条件式请求 ,常见实现有 Last-Modified 和 ETag 两种。

const conditional = require('koa-conditional-get');
const etag = require('koa-etag');
const Koa = require('koa');
const app = new Koa();

// use it upstream from etag so
// that they are present

app.use(conditional());

// add etags

app.use(etag());

koa-bodyparser

解析 HTTP 主体

var Koa = require('koa');
var bodyParser = require('koa-bodyparser');

var app = new Koa();
app.use(bodyParser());

app.use(async ctx => {
  // the parsed body will store in ctx.request.body
  // if nothing was parsed, body will be an empty object {}
  ctx.body = ctx.request.body;
});

koa-static

静态服务器

import staticServe from 'koa-static'

app.use(staticServe(path.join(__dirname, '../assets'), {
    maxAge: 24 * 60 * 60
}))

koa-views

模板渲染中间件

const views = require('koa-views');

app.use(views(path.join(__dirname, 'views')));

koa-mount

通过 URL 挂载,将其他 Koa 实例挂在到一个主实例中

const a = new Koa();

const b = new Koa();

app.use(mount('/hello', a));
app.use(mount('/world', b));

koa-connect

兼容 Express 中间件可以在 Koa 中使用

import connect from 'koa-connect'

app.use(c2k(connectMiddlware))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

HTTP Essentials

HTTP Essentials

Stephen A. Thomas、Stephen Thomas / Wiley / 2001-03-08 / USD 34.99

The first complete reference guide to the essential Web protocol As applications and services converge and Web technologies not only assume HTTP but require developers to manipulate it, it is be......一起来看看 《HTTP Essentials》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具