前言
這是該系列文章的第九篇,主要介紹koa2框架的使用
hello world
安裝:npm i koa
const koa = require('koa');
const app = new koa();
app.use(async (ctx) => {
ctx.body = 'hello world'
})
app.listen(3000, () => {
console.log('success on port 3000...');
})
開放靜態資源
安裝:npm i koa-static
使用
const Koa=require('koa');
const path=require('path');
const static = require('koa-static');
const app=new Koa();
//static配置,根目錄下要有一個public文件夾,也可自定義
app.use(static( path.join( __dirname, 'public') ));
app.listen(3000,()=>{
console.log('run server --')
});
效果圖:訪問127.0.0.1:3000/logo.jpg
路由
安裝:npm i koa-router
使用
const Koa=require('koa');
const router = require('koa-router')();
const app=new Koa();
router.get('/',async (ctx)=>{
ctx.body="<h1>home</h1>";
})
router.get('/news',async (ctx)=>{
ctx.body="<h1>news</h1>";
})
router.get('/newsinfo/:nid',async (ctx)=>{
ctx.body="新聞詳情"+ctx.params.nid;//獲取動態路由的傳值-ctx.params.nid
})
app.use(router.routes()); //掛載路由
app.use(router.allowedMethods());//錯誤處理相關操作
app.listen(3000,()=>{
console.log('run server---')
});
模板引擎
安裝:npm i art-template koa-art-template
使用
const Koa = require('koa');
const app = new Koa();
const template = require('koa-art-template');
template(app,
{
root:'./views',//視圖文件夾
extname: '.html',//模板格式
debug: process.env.NODE_ENV !== 'production'//非生產環境,開啓調試
}
);
app.use(
async function (ctx) {
await ctx.render('index', {
content: "hello koa-art-template"
});
}
);
app.listen(3000, () => {
console.log('run server --')
});
渲染:index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>koa-art-template</title>
</head>
<body>
<h1>{{content}}</h1>
</body>
</html>
效果圖
處理post請求
安裝:npm i koa- bodyparser
使用
const Koa = require('koa');
const router = require('koa-router')();
const views = require('koa-views');
const bodyParser = require('koa-bodyparser');
const app = new Koa();
/*應用ejs模板引擎*/
app.use(views('views', {
extension: 'ejs'
}))
//配置post bodyparser的中間件
app.use(bodyParser());
router.get('/', async (ctx) => {
await ctx.render('index');
})
//接收post提交的數據
router.post('/doAdd', async (ctx) => {
console.log(ctx.request.body);
ctx.body = ctx.request.body; //獲取表單提交的數據
})
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000, () => {
console.log('run server')
});
圖片上傳
const path = require('path');
const fs = require('fs');
//上傳圖片公共代碼塊
const _commonCode = (file, ctx) => {
// 創建可讀流
const reader = fs.createReadStream(file.path);
//設置目標上傳路徑
let target = path.resolve(__dirname, `../public/img/${ctx.request.body.layout_id}`)
//以layout_id命名的文件夾若不存在,則創建
if (fs.existsSync(target) === false) {
fs.mkdirSync(target)
}
let filePath = target + `/${file.name}`
// 創建可寫流
const upStream = fs.createWriteStream(filePath);
// 可讀流通過管道寫入可寫流
reader.pipe(upStream);
}
// 該放方法需要傳入上下文ctx
exports.upload = (ctx) => {
// 上傳多個文件
const files = ctx.request.files.file; // 獲取上傳文件信息
const allowExtname = ['.png', '.jpg', '.jpeg', '.webp', '.bmp' ,'.gif' ];//支持的圖片格式
let filterPic = false;//是否存在不支持的圖片格式標識
const rejectExtname=[]//不支持的圖片格式數組
if (files.length > 1) {
for (let file of files) {
const extname = path.extname(file.name);// 獲取上傳文件拓展名
if (allowExtname.includes(extname)) {
_commonCode(file, ctx);//圖片格式符合,進行上傳
}else{
filterPic = true;//圖片格式不符合條件,更改標識
rejectExtname.push(extname)//填充不支持的圖片格式數組
}
}
} else {
const file = ctx.request.files.file;
const extname = path.extname(file.name);// 獲取上傳文件拓展名
if (allowExtname.includes(extname)) {
_commonCode(file, ctx);//圖片格式符合,進行上傳
}else{
filterPic = true;//圖片格式不符合條件,更改標識
rejectExtname.push(extname) //填充不支持的圖片格式數組
}
}
}
session
安裝:npm i koa-session
使用
const Koa = require('koa');
const router = require('koa-router')();
const template = require('koa-art-template');
const session = require('koa-session');
const app = new Koa();
//配置 koa-art-template模板引擎
template(app, {
root: './views', // 視圖的位置
extname: '.html', // 後綴名
debug: process.env.NODE_ENV !== 'production' //是否開啓調試模式
});
app.keys = ['some secret hurr']; /*cookie的簽名*/
//配置session的中間件
app.use(session({ maxAge: 10000}, app)); // maxAge--cookie的過期時間
router.get('/', async (ctx) => {
//獲取session
if (!ctx.session.userName) {
ctx.body = "尚未登陸";
return;
}
await ctx.render('index', {
user: {
name: ctx.session.userName
}
});
})
router.get('/login', async (ctx) => {
//設置session
ctx.session.userName = '張三';
ctx.body = "登錄成功";
})
router.get('/loginOut', async (ctx) => {
if (ctx.session.userName) {
//設置session
ctx.session.userName = null;
ctx.body = "您已退出登陸";
}else{
ctx.body = "尚未登陸";
}
})
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000, () => {
console.log('run server --')
});