npm init -y
npm install koa koa-router -S
npm install nodemon -D
package.json 配置 "start": "nodemon app.js"
{ "name": "jiekolianxi", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "nodemon app.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "koa": "^2.13.4", "koa-body": "^4.2.0", "koa-router": "^10.1.1", "mongoose": "^6.1.1" }, "devDependencies": { "nodemon": "^2.0.15" } }
app.js
const Koa = require('koa'); const Router = require('koa-router'); const app = new Koa(); const router = new Router(); router.get('/', ctx => { ctx.body = "Hello Koa !!!!" }) app.use(router.routes()).use(router.allowedMethods()); app.listen(3000, () => { console.log('正在监听3000端口的服务') })
./routers/users.js
const Router = require('koa-router'); const router = new Router({ prefix: '/users' }); router.get('/', ctx => { ctx.body = "我是用户列表" }) router.get('/:id', ctx => { console.log(ctx.params.id) ctx.body = "获取某一个用户" }) router.post('/', ctx => { ctx.body = "添加一个新的用户" }) router.put('/:id', ctx => { ctx.body = "修改用户成功" }) router.delete('/:id', ctx => { ctx.body = "删除用户成功" }) module.exports = router.routes();
const Koa = require('koa'); const Router = require('koa-router'); const usersRouter = require('./routers/users.js') const app = new Koa(); const router = new Router(); router.get('/', ctx => { ctx.body = "Hello Koa !!!!" }) router.use(usersRouter); app.use(router.routes()).use(router.allowedMethods()); app.listen(3000, () => { console.log('正在监听3000端口的服务') })
query传参
调用接口
后端解析参数
router.get('/', ctx => { console.log(ctx.query.id) ctx.body = "我是用户列表" })
params传参
调用接口
后端解析参数
router.get('/:id', ctx => { console.log(ctx.params.id) ctx.body = "获取某一个用户" })
body传参
router.post('/', ctx => { let { name, age } = ctx.request.body; console.log(name, age); ctx.body = "添加一个新的用户" })
npm install koa-body -S
主程序需要添加
const koaBody = require('koa-body'); // 放在路由中间前面 app.use(koaBody()); router.use(usersRouter); app.use(router.routes()).use(router.allowedMethods());
./controller/usersControllers.js
// 获取用户列表 const getUserList = (ctx) => { console.log(ctx.query.id) ctx.body = "我是用户列表" } // 获取某一个用户 const getUser = (ctx) => { console.log(ctx.params.id) ctx.body = "获取某一个用户" } // 新增一个用户 const createUser = (ctx) => { let { name, age } = ctx.request.body; console.log(name, age); ctx.body = "添加一个新的用户" } // 修改一个用户 const updateUser = (ctx) => { ctx.body = "修改用户成功" } // 删除一个用户 const deleteUser = (ctx) => { ctx.body = "删除用户成功" } module.exports = { getUserList, getUser, createUser, updateUser, deleteUser }
1.用cmd命令以管理员身边运行 mongodb
输入 net start mongodb
2.连接 MongoDB 的地址
Mongoose 5.0 中文文档http://www.mongoosejs.net/docs/index.html或者 使用
const Koa = require('koa'); const Router = require('koa-router'); const koaBody = require('koa-body'); const mongoose = require('mongoose'); const usersRouter = require('./routers/users.js') mongoose.connect('mongodb://localhost/admin'); var db = mongoose.connection; db.on('error', console.error.bind(console, '连接失败!!!')); db.once('open', function () { console.log('连接成功!!!') });
./models/usersSchema.js
const mongoose = require('mongoose'); const { Schema, model } = mongoose; const usersSchema = new Schema({ __v: { type: String, select: false }, name: { type: String, required: true }, email: { type: String, default: '' }, password: { type: String, required: true, select: false }, date: { type: Date, default: Date.now } // 注册时间 }) module.exports = model('Users', usersSchema)
usersControllers.js
const Users = require('../models/usersSchema.js') // 获取用户列表 const getUserList = async ctx => { ctx.body = await Users.find(); } // 获取某一个用户 const getUser = async ctx => { console.log(ctx.params.id) const user = await Users.findById(ctx.params.id); if (!user) { ctx.throw(404, '用户不存在') } ctx.body = user } // 新增一个用户 const createUser = async ctx => { let { name } = ctx.request.body; const user = await Users.findOne({ name }); if (user) { ctx.throw(405, '已存在该用户!!!') } else { ctx.body = await new Users(ctx.request.body).save(); } } // 修改一个用户 const updateUser = async ctx => { let { id } = ctx.params const user = await Users.findByIdAndUpdate(id, ctx.request.body); if (!user) { ctx.throw(404, '用户不存在!!!') } ctx.status = 200 ctx.body = { msg: '修改成功' } } // 删除一个用户 const deleteUser = async ctx => { let { id } = ctx.params const user = await Users.findByIdAndDelete(id); if (!user) { ctx.throw(404, '用户不存在!!!') } ctx.status = 200 ctx.body = { msg: '删除成功' } } module.exports = { getUserList, getUser, createUser, updateUser, deleteUser }
传入一个用户id
body里面添加用户信息
可以只传自己需要修改的字段,id还是在地址栏上传的,这一点需要注意
传入一个id
./routers/uploads.js
const path = require('path'); const Router = require('koa-router'); const router = new Router({ prefix: "/uploads" }); /** * @route GET api/uploads * @desc 测试接口地址 * @access 接口是公开的 */ router.post('/', ctx => { const file = ctx.request.files.file; const basename = path.basename(file.path); ctx.body = { url: `${ctx.origin}/uploads/${basename}` }; }) module.exports = router.routes();
npm install koa-static
要创建一个public 目录 里面 创建一个 uploads文件
const Koa = require('koa'); const Router = require('koa-router'); const koaBody = require('koa-body'); const KoaStatic = require('koa-static') const path = require('path') const mongoose = require('mongoose'); const usersRouter = require('./routers/users.js') const uploadsRouter = require('./routers/uploads.js') mongoose.connect('mongodb://localhost/admin'); var db = mongoose.connection; db.on('error', console.error.bind(console, '连接失败!!!')); db.once('open', function () { console.log('连接成功!!!') }); const app = new Koa(); const router = new Router(); router.get('/', ctx => { ctx.body = "Hello Koa !!!!" }) // 静态资源访问的功能 app.use(KoaStatic(path.join(__dirname, 'public'))) app.use(koaBody({ multipart: true, formidable: { uploadDir: path.join(__dirname, '/public/uploads'), keepExtensions: true } })); router.use(uploadsRouter); router.use(usersRouter); app.use(router.routes()).use(router.allowedMethods()); app.listen(3000, () => { console.log('正在监听3000端口的服务') })