【知识整理】Node.js-Koa之Web App的功能

来源:互联网 发布:国家网络质量管理 编辑:程序博客网 时间:2024/04/30 13:00
一。Web App的功能

1.Cookies:用来读写cookie

const main = function(ctx){const n = Number(ctx.cookie.get('view') || 0) +1;ctx.cookid.set('view', n);ctx.response.body = n + 'view';}
2.表单:koa-body模块可以用来从post请求的数据体里面提取键值对。

const koaBody = require('koa-body');const main = async function(ctx){const body = ctx.request.body;if(!body.name){ctx.throw(400, '.name required');}ctx.body = {name : body.name};}app.use(koaBody());
3.koa-body模块可以用来处理文件上传。
const path = require('path');const koaBody = require('koa-body');const main = async function(ctx){const tmpDir = path.resolve('.');const filePaths = [];const files = ctx.request.body.files || {};for(let key in files){const file = files[key];const filePath = path.join(tmpDir, file.name);const reader = fs.createReadStream(file.path);const writer = fs.createWriteStream(filePath);reader.pipe(writer);filepaths.push(filePath);}ctx.body = filePaths;}app.use(koaBody({multipart: true}));




原创粉丝点击