• kora 简单使用实现Api接口 以及mongodb简单使用


    //api.js
    const Koa = require('koa'); const router = require('koa-router')(); //路由 const bodyParser = require('koa-bodyparser'); //解析原始request请求 const fs = require('fs'); //文件读取 const cors = require('koa2-cors'); //设置cors头 const app = new Koa; /** * 数据库连接 */ var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/admin', {'useNewUrlParser': true}); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log('数据库连接成功') /** * Schema 用来定义存储在document 中的属性,并且赋予他们校验的规则,和默认值 */ var kittySchema = new mongoose.Schema({ name: String }); kittySchema.methods.speak = function () { var greeting = this.name ? "Meow name is " + this.name : "I don't have a name"; console.log(greeting); } /** * 定义模型 */ var Kitten = mongoose.model('Kitten', kittySchema); /** * 模型实例 */ var silence = new Kitten({ name: 'Silence' }); console.log(silence.name); // 'Silence' silence.save(); //插库 var fluffy = new Kitten({ name: 'fluffy' }); fluffy.save(function (err, fluffy) { if (err) return console.error(err); fluffy.speak(); }); }); app.use(bodyParser()); app.use(cors({ origin: function (ctx) { return '*'; } })); let files = fs.readdirSync(__dirname + '/controllers'); let js_files = files.filter((f)=>{ return f.endsWith('.js'); }); for( let f of js_files ){ console.log(`process conteoller : ${f} ...`); let mapping = require(__dirname + '/controllers/' + f ); for ( let url in mapping ){ if( url.startsWith('GET ')){ //如果url类似'GET xxx' let path = url.substring(4); router.get(path,mapping[url]); }else if( url.startsWith('POST ') ){ //如果url类似'POST xxx' let path = url.substring(5); console.log('请求方式是:',path); router.post(path,mapping[url]); } } } app.use(router.routes()); app.listen(8888); console.log('app started at port 8888...');

  • 相关阅读:
    ping 介绍
    密码学系列——简介密码学
    ActiveMQ c# 系列——进阶实例(三)
    转:LVS简介
    口罩与mask------看东西方文化差异
    Java设计模式之单利模式(Single Pattern)
    Cadence OrCAD Cpature创建Title Block
    终极干货,数组去重且显示每一个数据重复的次数
    LeetCode 64. 最小路径和 | Python
    LeetCode 剑指 Offer 11. 旋转数组的最小数字 | Python
  • 原文地址:https://www.cnblogs.com/cuikaitong/p/10615393.html
Copyright © 2020-2023  润新知