koa-body
一個(gè)功能齊全的koa體解析器中間件。支持多部分、urlencoded和json請(qǐng)求主體。提供與Express的bodyParser-multer相同的功能。
const koaBody = require('koa-body');
app.use(koaBody({
multipart: true,
formidable: {
uploadDir: path.join(__dirname, "/public/uploads"), //上傳文件存放地址
keepExtensions: true,
},
}));
koa-parameter
koa的參數(shù)驗(yàn)證中間件,由參數(shù)提供支持。
const parameter = require('koa-parameter');
parameter(app);
//Usage
app.use(async function (ctx) {
ctx.verifyParams({
name: 'string',
password: 'string'
});
});
koa-static
Koa靜態(tài)文件服務(wù)中間件
const koaStatic = require('koa-static');
app.use(koaStatic(path.join(__dirname, "public")));
// 注入public為靜態(tài)資源庫
@koa/cors
Koa跨域中間件
const cors = require("@koa/cors");
app.use(
cors({
origin: function (ctx) {
//設(shè)置允許來自指定域名請(qǐng)求
if (ctx.url === "/api") {
return "*"; // 允許來自所有域名請(qǐng)求
}
return "http://localhost:8000"; //只允許http://localhost:8080這個(gè)域名的請(qǐng)求
},
maxAge: 5, //指定本次預(yù)檢請(qǐng)求的有效期,單位為秒。
credentials: true, //是否允許發(fā)送Cookie
allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], //設(shè)置所允許的HTTP請(qǐng)求方法
allowHeaders: ["Content-Type", "Authorization", "Accept"], //設(shè)置服務(wù)器支持的所有頭信息字段
exposeHeaders: ["WWW-Authenticate", "Server-Authorization"], //設(shè)置獲取其他自定義字段
})
);
jsonwebtoken && koa-jwt
jwt.sign(負(fù)載內(nèi)容, 加密Key值, [參數(shù), 回調(diào)])
var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, '加密Key值');
// sign with RSA SHA256
var privateKey = fs.readFileSync('private.key');
var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256'});
options:
algorithm加密模式,(默認(rèn): HS256)expiresIn:過期時(shí)間,以秒或描述時(shí)間跨度的字符串表示。例如:60、“2天”、“10小時(shí)”、“7天”。數(shù)值被解釋為秒計(jì)數(shù)。如果使用字符串,請(qǐng)確保提供時(shí)間單位(天、小時(shí)等),否則默認(rèn)使用毫秒單位 ("120"意味"120毫秒").notBefore:以秒或描述時(shí)間跨度的字符串表示。例如:60、“2天”、“10小時(shí)”、“7天”。數(shù)值被解釋為秒計(jì)數(shù)。如果使用字符串,請(qǐng)確保提供時(shí)間單位(天、小時(shí)等),否則默認(rèn)使用毫秒單位
("120"意味"120毫秒")。
iat (issued at) 簽發(fā)日期
koa-jwt此模塊允許您在Koa(node.js)應(yīng)用程序中使用jsonweb令牌對(duì)HTTP請(qǐng)求進(jìn)行身份驗(yàn)證。
var jwt = require('koa-jwt');
// 中間件啟用驗(yàn)證并排除'/public'路徑
app.use(jwt({ secret: '加密Key值' }).unless({ path: [/^\/public/] }));
// 無驗(yàn)證的中間件
app.use(function(ctx, next){
if (ctx.url.match(/^\/public/)) {
ctx.body = 'unprotected\n';
} else {
return next();
}
});
// 受驗(yàn)證的中間件
app.use(function(ctx){
if (ctx.url.match(/^\/api/)) {
ctx.body = 'protected\n';
}
});