http获取请求参数https://www.eggjs.org/zh-CN/basics/controller
获取post请求参数
const query = ctx.request.body;
app\model\eventInfo.js
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const eventSchema = new Schema({
title: {
type: String,
},
subTitle: {
type: String,
},
createDate: {
type: String,
},
publishDate: {
type: String,
},
content: {
type: String,
},
});
return mongoose.model('EventInfo', eventSchema, 'event');
};
app\service\eventInfo.js
'use strict';
const Service = require('egg').Service;
class EventService extends Service {
async getList() {
const {
ctx,
} = this;
const results = await ctx.model.EventInfo.find();
return results;
}
async itemAdd() {
const {
ctx,
} = this;
// 获取post请求参数
const query = ctx.request.body;
let results;
console.log('ctx', ctx.request.body);
if (Object.keys(query).length) {
const res = await ctx.model.EventInfo.create(query);
console.log('itemAdd', results);
if (res) {
results = true;
} else {
results = false;
}
}
return results;
}
async bitchAdd() {
const {
ctx,
} = this;
// 获取post请求参数
const query = ctx.request.body.list;
console.log('query', query);
let results;
if (query.length) {
const res = await ctx.model.EventInfo.create(query);
if (res) {
results = true;
} else {
results = false;
}
}
return results;
}
}
module.exports = EventService;
app\controller\eventInfo.js
'use strict';
const {
Controller,
} = require('egg');
class EventController extends Controller {
// 查询数据
async list() {
const {
ctx,
} = this;
const result = await ctx.service.eventInfo.getList();
ctx.body = {
list: result,
};
}
async addItem() {
const {
ctx,
} = this;
const results = await ctx.service.eventInfo.itemAdd();
// console.log('add', results);
if (results) {
ctx.body = {
code: 0,
data: {
msg: 'success',
},
};
} else {
ctx.body = {
code: 4001,
data: {
msg: 'fail',
},
};
}
}
async addItems() {
const {
ctx,
} = this;
const results = await ctx.service.eventInfo.bitchAdd();
console.log('add', results);
if (results) {
ctx.body = {
code: 0,
data: {
msg: 'success',
},
};
} else {
ctx.body = {
code: 4001,
data: {
msg: 'fail',
},
};
}
}
}
module.exports = EventController;
app\router\eventInfo.js
module.exports = app => {
const { router, controller } = app;
router.get('/event', controller.eventInfo.list);
router.post('/event', controller.eventInfo.addItem);
};
插入一条数据图示
插入多条数据图示