const Koa = require('koa');
const Router = require('koa-router');
const bodyparser = require('koa-bodyparser');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
let _url = "mongodb://127.0.0.1:27017/people"
let app = new Koa();
let router = new Router();
var People = new Schema({
name: String,
address: String,
})
var Model = mongoose.model('person',People)
//解決跨域
app.use(async (ctx,next) => {
ctx.set('Access-Control-Allow-Origin',"*");//容許全部路徑的訪問。
ctx.set('Access-Control-Allow-Methods',"OPTIONS, GET, PUT, POST, DELETE");//容許訪問的方法
ctx.set('Access-Control-Allow-Headers',"x-requested-with, accept, origin, content-type");//容許訪問的headers
ctx.set('Content-type',"application/json");//接受的類型
await next();//轉移給下一個中間件。
})
app.use(bodyparser())
router.post('/test',async (ctx) => {
let postData= ctx.request.body;
await mongoose.connect(_url,{ useNewUrlParser: true },function(err) {
if(err){
console.log(err,'鏈接失敗');
}
else{
console.log('鏈接成功');
var doc1 = new Model(postData);
doc1.save(); //這一步驟是必須的!save函數中能夠使用cb
ctx.body = {
status:200,
msg:'success'
}
}
});
})
router.get('/test/:name',async (ctx) => {
const parms = ctx.params
await mongoose.connect(_url,{ useNewUrlParser: true },function(err) {
if(err){
console.log(err,'鏈接失敗');
}
else{
let res = Model.find(parms);
console.log(res)
// console.log('鏈接成功');
// var doc1 = new Model(postData);
// doc1.save(); //這一步驟是必須的!save函數中能夠使用cb
// ctx.body = {
// status:200,
// msg:'success'
// }
}
});
})
app.use(router.routes()).use(router.allowedMethods())
app.listen(27017,()=>{
console.log('[demo] server is starting at port 27017');
})