1-1 构建环境

  1. yarn init -y
  2. yarn add koa koa-router koa-body koa-static koa-mongodb

1-2 modules-index.js

const {MongoClient}=require('mongodb');
const url='mongodb://123.60.82.25:12021';
const client=new MongoClient(url)
const dbName='student';
async function main(){
    await client.connect();
    console.log('Connected successfully to server');
    const db =client.db(dbName);
    const collection =db.collection('username');
    return collection;
}
module.exports=main;

1-3 配置路由app.js

const koa =require("koa");
const app=new koa();
const router =require("koa-router")();
const main =require('./models')
router.get("/find",async ctx=>{
    var collection=await main();
    var result=await collection.find().toArray();
    console.log(result);
})
app.use(router.routes());
app.listen(4000);

image.png
image.png

1-4 添加一条数据到数据库中

image.png

router.get("/add",async ctx=>{
        var collection=await main();
        var obj={
            name:"dww",
            age:17
        }
        var res =await collection.insertOne(obj);
        console.log(res);
    })

image.png

1-5 解决重复数据添加

image.png

router.get("/add",async ctx=>{
            var collection=await main();
            var obj={
                name:"dww",
                age:17
            }
            var res =await collection.find({name:obj.name}).toArray();
            if(res.length){
                ctx.body="数据库中已添加了这位同学"
            }else{
                var result=await collection.insertOne(obj);
            }
            console.log(result);
        })

1-6 表单提交数据

image.png

const koaBody = require("koa-body");


router.post("/doForm",async ctx=>{
            console.log(ctx.request.body);
                      var {name,age}=ctx.request.body;
            const collection=await main();
            await collection.insertOne({name,age});
            await ctx.redirect("/find")
        })


app.use(koaBody())

1-7 解决请求数据时的跨域

app.use(async (ctx,next)=>{
        ctx.set("Access-Control-Allow-Origin","*");
        await next();
    })

1-8 提交图片

image.png

router.post("/doForm",async ctx=>{
            console.log(ctx.request.body);
            var {name,age}=ctx.request.body;
            age=Number(age);
           var filename=ctx.request.files.logo.path
           console.log(filename);
            var reader=fs.createReadStream(filename);
            var uploadFile=`./static/${path.basename(filename)}`;
            var writer=fs.createWriteStream(uploadFile);
            reader.pipe(writer)
            var logo=ctx.origin+"/"+path.basename(filename);

            const collection=await main();
            await collection.insertOne({name,age,logo});
            await ctx.redirect("/find")            
        })

image.png