1.使用中间件
- 创建文件夹
mkdir useragent && cd useragent - 安装插件
cnpm install -S koa koa-useragent
- 新建index.js
const Koa = require("koa");
const app = new Koa();
const userAgent = require("koa-useragent");
app.use(userAgent);
app.use(async (ctx, next) => {
console.log(require("util").inspect(ctx.userAgent));
});
app.listen(3000);
- 运行服务器
node index.js - 打开浏览器
输入 127.0.0.1:3000,结果如下:
{ isAuthoritative: true,
isMobile: false,
isTablet: false,
isiPad: false,
isiPod: false,
isiPhone: false,
isAndroid: false,
isBlackberry: false,
isOpera: false,
isIE: false,
isEdge: false,
isIECompatibilityMode: false,
isSafari: false,
isFirefox: false,
isWebkit: false,
isChrome: true,
isKonqueror: false,
isOmniWeb: false,
isSeaMonkey: false,
isFlock: false,
isAmaya: false,
isPhantomJS: false,
isEpiphany: false,
isDesktop: true,
isWindows: true,
isLinux: false,
isLinux64: false,
isMac: false,
isChromeOS: false,
isBada: false,
isSamsung: false,
isRaspberry: false,
isBot: false,
isCurl: false,
isAndroidTablet: false,
isWinJs: false,
isKindleFire: false,
isSilk: false,
isCaptive: false,
isSmartTV: false,
isUC: false,
isElectron: false,
isFacebook: false,
isAlamoFire: false,
silkAccelerated: false,
browser: 'Chrome',
version: '70.0.3538.110',
os: 'Windows 10.0',
platform: 'Microsoft Windows',
geoIp: {},
electronVersion: '',
source:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36' }
2.创建中间件
每一个中间件会接收ctx和next两个参数,next是下一个回调的Promise,而ctx是koa封装的上下文,这个对象包含响应和请求的所有方法,当我们想添加一些方法的时候,可以直接过载到ctx对象上.
我们尝试创建一个在控制台中输出当前访问url的中间件
- 创建log.js
module.exports = options => {
if (!options.format) {
console.error("需要传递format函数");
}
return async (ctx, next) => {
console.log(options.format(ctx.url));
await next();
};
};
- index.js
const Koa = require("koa");
const app = new Koa();
const userAgent = require("koa-useragent");
const log = require("./log");
const config = { format: text => `========= ${text}=========` };
app.use(userAgent);
app.use(log(config));
app.use(async (ctx, next) => {
console.log(require("util").inspect(ctx.userAgent));
});
app.listen(3000);
- 启动服务器
node index.js - 访问
http://127.0.0.1:3000/home
结果如下:
========= /home=========
通常自定义的中间件需要产地配置项,所以开发的中间件插件通常是两层函数,一层函数来传递配置项,一层是kos.js中间件,注意一定要调用next,否则无法调用后续中间件.