模板
koa编写后端数据
项目结构
index.js
const Koa = require('koa');
const mongoose = require('mongoose');
const cors = require('koa2-cors');
const db = 'mongodb://test:123456@localhost:27017/test' //mongoose 地址
const router = require('./router/router')()
const bodyParser = require('koa-bodyparser')//中间件,
mongoose.connect(db,{useNewUrlParser:true})//链接mongoose
const app = new Koa();
app.use(cors())//跨域处理
app.use(bodyParser({enableTypes:['json', 'form', 'text']}));
app.use(router.routes())
.use(router.allowedMethods())
app.use(async(ctx)=>{
ctx.body="66666666666666"
})
app.listen(8808,()=>{
console.log('server is runing on 8808')
})
Models.js
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var uSchema = new Schema({
email:String,
name:String
})
mongoose.model('usercols',uSchema)
exports.User = mongoose.model('usercols')
User.js
const {User} = require('./models.js')
exports.GetUser=async (ctx,next)=>{
const email = ctx.query.email;
let data = await User.findOne({
email:email
})
ctx.body={
status:data ? 1 : 0,
data:data
}
}
exports.SaveUser=async(ctx,next)=>{
const email= ctx.request.body.email;
const name=ctx.request.body.name;
if(!email || !name) return ctx.body={status:0,message:"邮箱错误"}
let data = await User.findOne({
email:email
})
if (data) {
ctx.body={
status:0,
data:"用户已存在"
}
} else {
try {
var save = await User.create({"email":email,"name":name});
ctx.body={
status:1,
data:save
}
} catch (error) {
ctx.body={
status:0,
data:error
}
}
}
}
router.js
const Router = require('koa-router');
const User =require('./User.js')
module.exports=function(){
const router = new Router();
router.get('/u/have',User.GetUser)//查询用户是否存在
router.post('/u/register',User.SaveUser)//注册用户
return router
}
源码地址:https://github.com/wangweiruning/koa-moongodb.git
git clone https://github.com/wangweiruning/koa-moongodb.git
cd koa2
yarn install
node index.js 启动