const Koa = require('koa');
const Router = require('koa-router');
const multer = require('koa-multer');
const mongoose = require('mongoose');
const ejs = require('ejs');
const bodyParser = require('koa-bodyparser');
// 连接MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true });
// 创建Koa实例
const app = new Koa();
const router = new Router();
// 配置ejs模板引擎
app.context.render = co.wrap(ejs.renderFile);
// 配置bodyParser中间件
app.use(bodyParser());
// 配置文件上传
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
const upload = multer({ storage: storage })
// 创建mongoose模型
const PostSchema = new mongoose.Schema({
title: String,
content: String
});
const Post = mongoose.model('Post', PostSchema);
// 处理文件上传
router.post('/upload', upload.single('file'), async (ctx, next) => {
// 文件上传后的处理逻辑
ctx.body = { success: true, file: ctx.file };
});
// 创建博客
router.post('/posts', async (ctx, next) => {
const post = new Post(ctx.request.body);
await post.save();
ctx.redirect('/');
});
// 获取博客列表
router.get('/', async (ctx, next) => {
const posts = await Post.find();
await ctx.render('index', { posts: posts });
});
// 使用路由中间件
app.use(router.routes());
app.use(router.allowedMethods());
// 监听3000端口
app.listen(3000);
console.log('Server is running on port 3000');
这段代码示例展示了如何使用Koa框架结合ejs模板引擎、multer文件上传中间件和mongoose操作MongoDB。代码中包含了文件上传、博客发布、博客列表展示等常见Web开发功能,并且使用了async/await来简化异步代码。