• koa mog


    var MongoClient = require('mongodb').MongoClient;
    var url = 'mongodb://localhost:27017/lt';
    
    var mongoose = require('mongoose')
    var Schema = mongoose.Schema
    
    mongoose.connect('mongodb://localhost:27017/student',{
        useNewUrlParser: true 
    })
    
    //监听数据库连接状态
    mongoose.connection.once('open',()=>{
        console.log('数据库连接成功……')
    })
    
    mongoose.connection.once('close',()=>{
        console.log('数据库断开……')
    })
    
    
    const koa = require('koa');
    const Router = require('koa-router');
    let koabody = require('koa-body');
    
    const fs = require('fs')
    
    const app = new koa();
    const router = new Router();
    const session = require('koa-session');
    
    
    app.keys = ['some secret hurr'];
    
    const path = require('path')  
    const static = require('koa-static');
    // 配置静态web服务的中间件
    app.use(static(path.join(__dirname,'./imgs')));
    
    //app.use(session(CONFIG, app));
    
    const port = process.env.PORT || 5001;
    
    router.get("/",async ctx => {
        ctx.body = {msg:'Hello koa Interfaces'}
    })
    router.get("/api/",async ctx => {
        ctx.body = {msg:'Hello koa Interfaces api'}
    })
    
    //let Movie = require('./model/Movie');
    
    var schemaArticle = new mongoose.Schema({
        title:String,
        type:String,
        content:String,
        time:String
    })
    var article = mongoose.model('article',schemaArticle)
    
    router.get("/api/list",async ctx => {
    
        let docs = await article.find();
        //console.log(docs)
        ctx.body = docs
      
    })
    
    router.post('/api/add', async (ctx, next) => {
        let row =  ctx.request.body;
        
        console.log(row.title)
        //console.log(row.img)
         let now = new Date();
        let tt = {
                title:row.title,
                content:row.content,
                type:row.type?row.type:'',
                time:now.toLocaleString()
    
            }
        console.log(tt)
         
        await article.create(tt)
        ctx.response.body = {code:0};
    })
    
    
    app.use(koabody({
        multipart: true,
        formidable: {
            maxFileSize: 200*1024*1024    // 设置上传文件大小最大限制,默认2M
        },
        formLimit:20*1024*1024,
    }));
    
    app.keys = ['some secret hurr'];
    const CONFIG = {
        key: 'koa:sess',   //cookie key (default is koa:sess)
        maxAge: 3600000,  // cookie的过期时间 maxAge in ms (default is 1 days)
        overwrite: true,  //是否可以overwrite    (默认default true)
        httpOnly: true, //cookie是否只有服务器端可以访问 httpOnly or not (default true)
        signed: true,   //签名默认true
        rolling: false,  //在每次请求时强行设置cookie,这将重置cookie过期时间(默认:false)
        renew: false,  //(boolean) renew session when session is nearly expired,
    };
    
    app.use(session(CONFIG, app));
    
    app.use(router.routes()).use(router.allowedMethods);
    
    app.listen(port,() =>{
        console.log(`server started on ${port}!`)
    })
    
    //将stuSchema映射到一个MongoDB collection并定义这个文档的构成
    /*
    var stuSchema = new Schema({
        name: String,
        age: Number,
        gender:{
            type: String,
            default:'male'
        },
        addr: String
    })
    
    var stuModle = mongoose.model('student',stuSchema)
    
    stuModle.create({
        name:"小明",
        age:"20",
        addr:"天津"
    },(err,docs)=>{
        if(!err){
            console.log('插入成功'+docs)
        }
    })
    */

     setupProxy.js

    const proxy = require("http-proxy-middleware");
    const { createProxyMiddleware } = require('http-proxy-middleware');
    module.exports = function(app) {
        app.use(
            createProxyMiddleware("/api/", {
                //target: "http://10.229.72.32:8886/",
                target: "http://localhost:5001/",
                changeOrigin: true
            })
        );
    
    };
    add.js

    import './add.css' import {CustomDemo as MyEditor,g_Statecontent}from './editordemo' import {api} from '../common/axios' //let ret = await api.post(`/api/fault-action/modifyDevice?deviceID=${deviceID}&username=${globalStore.userName}&time=`+new Date().getTime(),val) let title=''; async function postMsg(){ let msg={title:title,content:g_Statecontent.toHTML()} if(title.length<10){ alert('标题要大于10') return; } console.log(msg) let ret = await api.post('/api/add?time='+new Date().getTime(),msg) debugger; if(ret == undefined) return; console.log('---------------->') console.log(ret) //this.setState({data:ret.list}) } function add(){ return( <div className="add"> <div className="head"> <label>返回</label> <label><b>添加文章</b></label> <label onClick={()=>{ const htmlContent = g_Statecontent.toHTML() // debugger // alert(title) // console.log(htmlContent) postMsg() }} >确定</label> </div> <li> <label>标题</label> <input type="text" name="title" onChange={(e)=>title = e.target.value} /> </li> <li> <label>类型</label> <select id="select-main"> <option>Hello</option> <option>HTML5</option> </select> </li> <li> <div id="myeditor1"> <MyEditor /> </div> </li> </div> ) } export default add;
    let gSetMsg = null;
    let gMsg = null;
    let gList = [];
    async function getMsg(){
        if(gMsg>2) return;
        let ret = await api.get('/api/list?time='+new Date().getTime())
       // debugger;
        if(ret == undefined) return;
        console.log('---------------->')
        console.log(ret)
       
        //this.setState({data:ret.list})
        gList = ret
        console.log(gList)
        gSetMsg(gMsg+1);
    }
     
    axios.js
    import axios from 'axios'
    const qs = require('qs')
    
    const api = {
        async get (url, data,vue) {
            try {
                let res = await axios.get(url, {params: data})
                res = res.data
                return new Promise((resolve) => {
                    //debugger;
                    //if (res.code === 0) 
                    if(1)
                    {
                        resolve(res)
                    } else {
                        if(-1 == res.sessionConnect){
                            
                            //vue.$router.push({path: '/login'});
                            return;
                        }
                        resolve(res)
                    }
                })
            } catch (err) {
                alert('服务器出错')
                console.log(err)
            }
        },
        async post (url, data,vue) {
            try {
                //debugger;
                let res = await axios.post(url, /*qs.stringify(data)*/data)
                res = res.data
                return new Promise((resolve, reject) => {
                    //debugger
                    //if (res.code === 0||res.code === 1) 
                    if(1)
                    {
                        if(-1 == res.sessionConnect){
                           // vue.$router.push({path: '/login'});
                        }
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            } catch (err) {
                // return (e.message)
                alert('服务器出错')
                console.log(err)
            }
        },
    }
    export { api }
  • 相关阅读:
    设计模式之Command
    UniversalApp
    swift做服务器端开发
    你不知道的函数floor pow round
    swift开发笔记31
    考试路线
    chrome google mozilla firefox bookmarks import export
    Astah Professional安装
    android studio 安装步骤
    vm安装diagram
  • 原文地址:https://www.cnblogs.com/cnchengv/p/14868017.html
Copyright © 2020-2023  润新知