1

温馨提示:看这篇文章前,确保之前的环境已经布置好了
1.主体文件结构如下
api/controller/UserController.js
api/module/User.js
api/router/userRouter.js
app.js

2.启动接口
运行:node app.js
有安装nodemon(热加载),nodemon app.js

3.代码
下方为app.js代码

const Koa = require('koa')
const fs = require('fs')
const bodyParser = require('koa-bodyparser');
const mongoose = require('mongoose');

const app = new Koa()

app.use(bodyParser())


const dbOptions = {
  useNewUrlParser: true,
  useUnifiedTopology: true
};
mongoose.connect("mongodb://localhost/test_ume",dbOptions).then(
  () => {console.info('MongoDB is ready');},
  err => {console.error('connect error:', err);}
);//test_ume 本地数据库名称


/*
*加载路由中间件
*/
const router = require('./routes/router')();
app.use(router.routes()).use(router.allowedMethods())

/*启动服务器*/
app.listen(3000, () => {
  console.log('[demo] route-use-middleware is starting at port 3000')
})

通过mongoose新建mongodb数据表Users
User.js代码如下:

const mongoose = require('mongoose');  
  
// 账户的数据库模型  
let UserSchema = new mongoose.Schema({  
  username:String,  
  password:String,  
  email:String  
});  
let User = mongoose.model('User',UserSchema)  
  
module.exports = User;

设置路由接口路径
router.js 代码如下

const Router = require('koa-router')  
const api = require('./userRouter')();  
  
module.exports = () => {  
  // 装载所有子路由  
  let router = new Router()  
  router.use('/api', api.routes(), api.allowedMethods())  
  return router;  
}

userRouter.js代码如下:

const Router = require('koa-router')  
const userController = require('../controllers/UserController');   
  
module.exports = () => {  
  const api = new Router()  
  api.get('/users', userController.getUserList)  
  api.get('/user/:id', userController.getUserInfoById)  
  api.get('/user/delete/:id', userController.deleteUser)  
  api.post('/user/update', userController.updateUser)  
  api.post('/user/add', userController.addUser)  

  return api;  
}

接口主要逻辑函数,定义返回对象
UserController.js代码如下:

const User = require('../models/User');  
const _ = require('loadsh');  
const xss = require('xss');  
  
exports.getUserList = async (ctx, next) => {  
  let val = null  
 const data = await User.find()  
  console.log('data', data)  
  const result = {  
      code:200,  
      response: data
  }  
  //console.info(ctx)  
  ctx.response.body = result  
  return result  
}  
exports.addUser = async (ctx, next) => {  
  let val = null  
 const jsonRequestBody =  ctx.request.body  
 console.info(jsonRequestBody.username)  
  let newUser = new User({  
      username: xss(_.trim(jsonRequestBody.username)),  
      password: xss(_.trim(jsonRequestBody.password)),  
      email: xss(_.trim(jsonRequestBody.email))  
  });  
  let data = await newUser.save();  
  console.log('data', data)  
  const result = {  
    code:200,  
  response: data,  
  ts: 12345  
  }  
  ctx.response.body = result  
  return result  
}  
exports.deleteUser = async (ctx, next) => {  
  let val = null  
 const data = await User.remove({_id: ctx.params.id})  
  //console.log('data', data)  
  const result = {  
    code:200,  
  response: data,  
  }  
  ctx.response.body = result  
  return result  
}  
exports.updateUser = async (ctx, next) => {  
  let val = null  
 const jsonRequestBody =  ctx.request.body  
 console.info(jsonRequestBody.username)  
  const data = await User.updateOne({
      _id: xss(_.trim(jsonRequestBody._id))},  
      { $set: {  
        "username": xss(_.trim(jsonRequestBody.username)),          "password": xss(_.trim(jsonRequestBody.password)),          "email": xss(_.trim(jsonRequestBody.email))  
       }
   })  
  console.log('data', data)  
  const result = {  
    code:200,  
  response: data,  
  }  
  ctx.response.body = result  
  return result  
}  
  
exports.getUserInfoById = async (ctx, next) => {  
  let val = null  
  console.log(ctx.params.id);  
  const data = await User.findOne({_id: ctx.params.id})  
  console.log('data', data)  
  const result = {  
    code:200,  
  response: data,  
  }  
  ctx.response.body = result  
  return result  
}

4.调试接口
工具:PostMan

新增用户
MKE_CVS)YXES3FNG4{RF1}C.png

查看所有用户列表
LHEO4ZA8F)O](J4FTBRH@]3.png

通过id查询用户信息
MG{5PC9122J1A1NT2O)4BEH.png

通过id修改用户信息
EN4}$$WTV38~F081G$XZ%EW.png

通过id删除用户信息,再次查询用户信息,验证删除了
GXK4P)2M]~}E6P~QBJ2~VWK.png
5]PL(X[QE67)R5~%{[HEL15.png

详细代码可参考:https://github.com/Linda0821/api-koa2-service
以上附链接:

学习 nodejs+mongodb+koa2 写接口(一) 环境布置
学习 nodejs+mongodb+koa2 写接口(二) koa2教程入门
学习 nodejs+mongodb+koa2 写接口(三) mongodb的增删改查
学习 nodejs+mongodb+koa2 写接口(四) 新建用户表,写用户的增删改查接口


Linda0821
62 声望4 粉丝