koa-body
一個(gè)功能齊全的koa體解析器中間件。支持多部分贞间、urlencoded和json請求主體茉帅。提供與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è)置允許來自指定域名請求
if (ctx.url === "/api") {
return "*"; // 允許來自所有域名請求
}
return "http://localhost:8000"; //只允許http://localhost:8080這個(gè)域名的請求
},
maxAge: 5, //指定本次預(yù)檢請求的有效期,單位為秒重虑。
credentials: true, //是否允許發(fā)送Cookie
allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], //設(shè)置所允許的HTTP請求方法
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ù)曹傀。如果使用字符串辐脖,請確保提供時(shí)間單位(天、小時(shí)等)皆愉,否則默認(rèn)使用毫秒單位 ("120"意味"120毫秒").notBefore:
以秒或描述時(shí)間跨度的字符串表示嗜价。例如:60、“2天”幕庐、“10小時(shí)”久锥、“7天”。數(shù)值被解釋為秒計(jì)數(shù)异剥。如果使用字符串瑟由,請確保提供時(shí)間單位(天、小時(shí)等)冤寿,否則默認(rèn)使用毫秒單位
("120"意味"120毫秒")歹苦。
iat (issued at) 簽發(fā)日期
koa-jwt此模塊允許您在Koa(node.js)應(yīng)用程序中使用jsonweb令牌對HTTP請求進(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';
}
});