Introduction and usage of commonly used official middleware
The Role of Middleware in Koa2
The core design philosophy of Koa2 is its middleware mechanism. Middleware is a function that takes two parameters: ctx
and next
. ctx
is the context object, encapsulating the request and response, while next
is a function that, when called, passes control to the next middleware. This mechanism allows developers to handle HTTP requests by combining different middleware functions.
app.use(async (ctx, next) => {
console.log('First middleware starts');
await next();
console.log('First middleware ends');
});
app.use(async (ctx, next) => {
console.log('Second middleware starts');
await next();
console.log('Second middleware ends');
});
koa-bodyparser
koa-bodyparser is used to parse request bodies, supporting JSON, form, and text formats. Installation:
npm install koa-bodyparser
Basic usage:
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const app = new Koa();
app.use(bodyParser());
app.use(async ctx => {
// Get POST request body
const body = ctx.request.body;
ctx.body = `Received data: ${JSON.stringify(body)}`;
});
Advanced configuration options:
app.use(bodyParser({
enableTypes: ['json', 'form', 'text'],
extendTypes: {
json: ['application/x-javascript'],
text: ['text/xml']
},
onerror: function(err, ctx) {
ctx.throw(422, 'body parse error');
}
}));
koa-router
koa-router is the most commonly used routing middleware for Koa2. Installation:
npm install @koa/router
Basic route definition:
const Router = require('@koa/router');
const router = new Router();
router.get('/', async (ctx) => {
ctx.body = 'Homepage';
});
router.get('/users/:id', async (ctx) => {
ctx.body = `User ID: ${ctx.params.id}`;
});
app.use(router.routes()).use(router.allowedMethods());
Nested routing example:
const users = new Router();
users.get('/', async (ctx) => {
ctx.body = 'User list';
});
const posts = new Router();
posts.get('/', async (ctx) => {
ctx.body = 'Post list';
});
const api = new Router();
api.use('/users', users.routes());
api.use('/posts', posts.routes());
app.use(api.routes());
koa-static
koa-static is used to serve static files. Installation:
npm install koa-static
Basic usage:
const static = require('koa-static');
app.use(static('public'));
Configuration options example:
app.use(static('public', {
maxage: 365 * 24 * 60 * 60 * 1000, // Cache for one year
hidden: true, // Allow access to hidden files
index: 'default.html', // Default file
defer: true // Execute other middleware first
}));
koa-views
koa-views is used for template rendering. Installation:
npm install koa-views
Usage with EJS template engine:
const views = require('koa-views');
app.use(views(__dirname + '/views', {
extension: 'ejs'
}));
app.use(async ctx => {
await ctx.render('index', {
title: 'Koa2 Views',
user: {name: 'John Doe'}
});
});
Support for multiple template engines:
app.use(views(__dirname + '/views', {
map: {
html: 'handlebars',
ejs: 'ejs'
}
}));
koa-session
koa-session provides session management functionality. Installation:
npm install koa-session
Basic configuration:
const session = require('koa-session');
app.keys = ['some secret key'];
app.use(session(app));
app.use(async ctx => {
if (ctx.path === '/login') {
ctx.session.user = {name: 'admin'};
ctx.body = 'Login successful';
} else if (ctx.path === '/user') {
ctx.body = ctx.session.user || 'Not logged in';
}
});
Custom storage:
const store = {
get(key) {
// Retrieve session from database
},
set(key, sess, maxAge) {
// Store session in database
},
destroy(key) {
// Delete session from database
}
};
app.use(session({
store,
key: 'koa:sess',
maxAge: 86400000,
autoCommit: true,
overwrite: true,
httpOnly: true,
signed: true,
rolling: false,
renew: false
}, app));
koa-helmet
koa-helmet enhances application security by setting various HTTP headers. Installation:
npm install koa-helmet
Basic usage:
const helmet = require('koa-helmet');
app.use(helmet());
Custom security policies:
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"]
}
},
hsts: {
maxAge: 31536000,
includeSubDomains: true
},
noCache: true
}));
koa-compress
koa-compress provides response compression. Installation:
npm install koa-compress
Basic configuration:
const compress = require('koa-compress');
app.use(compress({
filter: contentType => /text|javascript/i.test(contentType),
threshold: 2048,
gzip: {
flush: require('zlib').constants.Z_SYNC_FLUSH
},
deflate: {
flush: require('zlib').constants.Z_SYNC_FLUSH
},
br: false
}));
koa-logger
koa-logger provides request logging functionality. Installation:
npm install koa-logger
Usage example:
const logger = require('koa-logger');
app.use(logger());
// Custom log format
app.use(logger((str, args) => {
console.log(`[${new Date().toISOString()}] ${str}`);
}));
koa-json
koa-json beautifies JSON responses. Installation:
npm install koa-json
Basic usage:
const json = require('koa-json');
app.use(json());
app.use(ctx => {
ctx.body = {message: 'Hello', data: [1, 2, 3]};
// Outputs formatted JSON
});
Configuration options:
app.use(json({
pretty: process.env.NODE_ENV !== 'production',
param: 'pretty',
spaces: 2
}));
koa-respond
koa-respond simplifies HTTP responses. Installation:
npm install koa-respond
Usage example:
const respond = require('koa-respond');
app.use(respond());
app.use(ctx => {
if (ctx.accepts('html')) {
return ctx.html('<h1>Hello</h1>');
}
if (ctx.accepts('json')) {
return ctx.json({message: 'Hello'});
}
return ctx.send(400, 'Bad Request');
});
koa-cors
koa-cors handles cross-origin requests. Installation:
npm install @koa/cors
Basic configuration:
const cors = require('@koa/cors');
app.use(cors());
// Custom configuration
app.use(cors({
origin: 'https://example.com',
allowMethods: ['GET', 'POST', 'PUT'],
allowHeaders: ['Content-Type'],
exposeHeaders: ['X-Custom-Header'],
credentials: true,
maxAge: 3600
}));
koa-ratelimit
koa-ratelimit provides rate-limiting functionality. Installation:
npm install koa-ratelimit
Example using Redis storage:
const ratelimit = require('koa-ratelimit');
const Redis = require('ioredis');
app.use(ratelimit({
driver: 'redis',
db: new Redis(),
duration: 60000,
errorMessage: 'Too many requests',
id: ctx => ctx.ip,
headers: {
remaining: 'Rate-Limit-Remaining',
reset: 'Rate-Limit-Reset',
total: 'Rate-Limit-Total'
},
max: 100,
disableHeader: false
}));
koa-conditional-get
koa-conditional-get works with koa-etag to implement cache control. Installation:
npm install koa-conditional-get koa-etag
Usage example:
const conditional = require('koa-conditional-get');
const etag = require('koa-etag');
app.use(conditional());
app.use(etag());
app.use(ctx => {
ctx.body = {data: 'Content to be cached'};
});
koa-parameter
koa-parameter provides parameter validation. Installation:
npm install koa-parameter
Basic usage:
const parameter = require('koa-parameter');
app.use(parameter(app));
app.use(ctx => {
ctx.verifyParams({
name: {type: 'string', required: true},
age: {type: 'number', min: 18}
});
// Continue processing if validation passes
ctx.body = ctx.request.body;
});
Custom error handling:
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
if (err.code === 'INVALID_PARAM') {
ctx.status = 422;
ctx.body = {error: err.message, errors: err.errors};
}
}
});
koa-jwt
koa-jwt handles JSON Web Tokens. Installation:
npm install koa-jwt
Basic configuration:
const jwt = require('koa-jwt');
app.use(jwt({
secret: 'shared-secret',
key: 'jwtdata'
}).unless({
path: [/^\/public/]
}));
// Protected route
app.use(ctx => {
ctx.body = {
user: ctx.state.jwtdata
};
});
Custom token retrieval:
app.use(jwt({
secret: 'shared-secret',
getToken: ctx => ctx.cookies.get('token')
}));
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:同步与异步中间件的区别
下一篇:错误处理中间件的编写技巧