1.使用中間件
- 創(chuàng)建文件夾
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);
- 運(yùn)行服務(wù)器
node index.js - 打開瀏覽器
輸入 127.0.0.1:3000,結(jié)果如下:
{ 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.創(chuàng)建中間件
每一個(gè)中間件會(huì)接收ctx和next兩個(gè)參數(shù),next是下一個(gè)回調(diào)的Promise,而ctx是koa封裝的上下文,這個(gè)對(duì)象包含響應(yīng)和請(qǐng)求的所有方法,當(dāng)我們想添加一些方法的時(shí)候,可以直接過載到ctx對(duì)象上.
我們嘗試創(chuàng)建一個(gè)在控制臺(tái)中輸出當(dāng)前訪問url的中間件
- 創(chuàng)建log.js
module.exports = options => {
if (!options.format) {
console.error("需要傳遞format函數(shù)");
}
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);
- 啟動(dòng)服務(wù)器
node index.js - 訪問
http://127.0.0.1:3000/home
結(jié)果如下:
========= /home=========
通常自定義的中間件需要產(chǎn)地配置項(xiàng),所以開發(fā)的中間件插件通常是兩層函數(shù),一層函數(shù)來傳遞配置項(xiàng),一層是kos.js中間件,注意一定要調(diào)用next,否則無法調(diào)用后續(xù)中間件.