Node.js从入门到放弃(九)


前言


这是该系列文章的第九篇,主要介绍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

Node.js从入门到放弃(九)_图片格式

路由

安装: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>

效果图

Node.js从入门到放弃(九)_图片格式_02

处理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 --')
});