1.创建测试接口,并引入用户模型

根目录/routes/api/users.js

const Router = require('koa-router');
const router = new Router(); // 引入User
const User = require('../../models/User'); /**
* @route GET api/users/test
* @desc 测试接口地址
* @access 接口是公开的
*/
router.get('/test', async ctx => {
ctx.status = 200;
ctx.body = { msg: 'users works...' };
}); module.exports = router.routes();

2.创建用户模型

根目录/models/User.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema; // 实例化数据模板
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
require: true
},
avatar: {
type: String
},
date: {
type: Date,
default: Date.now
}
}); module.exports = User = mongoose.model('users', UserSchema);

3.引入测试接口

根路径/app.js

const Koa = require('koa');
const Router = require('koa-router');
const mongoose = require('mongoose'); // 实例化koa
const app = new Koa();
const router = new Router(); // 引入users.js
const users = require('./routes/api/users'); // 路由
router.get('/', async (ctx) => {
ctx.body = { msg: 'Hello Koa Interfaces' };
}); // config
const db = require('./config/keys').mongoURI; // 连接数据库
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => {
console.log('Mongodb Connected...');
})
.catch(err => {
console.log(err);
}) // 配置路由地址 localhist:5000/api/users
router.use('/api/users', users); // 配置路由
app.use(router.routes()).use(router.allowedMethods()); // 设置端口号
const port = process.env.PORT || 5000; // 监听端口号
app.listen(port, () => {
console.log(`server started on ${port}`)
})

.

05-11 22:38