koa2 mongdb 做后端接口的小demo
生活随笔
收集整理的這篇文章主要介紹了
koa2 mongdb 做后端接口的小demo
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
現在前端全棧里面有一種技術棧比較火
前端使用 vue 或者react 后端使用 koa2 mysql數據庫 或者mongdb做數據儲存
但是基本這樣的全棧教程 都要收費 收費就收費吧 但是 有沒有遇到非常好的教程
于是 準備硬著頭皮看別人項目的源碼 自己摸索 一步一步完成 koa mongdb的后端學習
下面就寫一個很簡單的koa mongdb 的數據庫寫入
user.js //這個頁面寫數據庫連接
var mongoose = require('mongoose') var Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/m_data') //m_data是我的數據庫名字 需要自己創建mongoose.connection.once('open',()=> {console.log("[mongoose]mongdb is start"); //監聽啟動 })var userSchema = new Schema({ //建表username: {type: String},password: {type: String},call: {type: Number},email: {type: String} })var user = mongoose.model('User',userSchema); //返回另一個Model實例module.exports = user //導出data.js
let koa = require('koa') var mongoose = require('mongoose') let User = require('./user') //導入上一個頁面的數據庫模塊 var bodyParser = require('koa-bodyparser'); //用于接受post請求的中間件 let app = new koa(); app.use(bodyParser()); app.use(async (ctx) => {if (ctx.url === '/' && ctx.method == 'GET') {//顯示表單頁面let html = `<h1>this is POST</h1><form action="http://localhost/" method="POST"><p>姓名: <input type="text" name="name"></p><p>年齡: <input type="text" name="age"></p><p>電話: <input type="text" name="call"></p><p>郵箱: <input type="text" name="email"></p><input type="submit" value="提交"></form>`ctx.body = html} else if (ctx.url === '/' && ctx.method == 'POST') {let postData = ctx.request.body;ctx.body = postData;console.log(postData);User.create({username: postData.name,password: postData.age,call: postData.call,email: postData.email},(err) => {if(err) returnconsole.log('插入成功');})} else {ctx.body = '<h1>404</h1>'let data = '';} }) app.listen(80,()=>{console.log('[koa] is start'); })對于有node基礎的人來說 這應該不難 稍微都能看懂 ,就是很簡單的數據庫寫入
假如你剛剛學習koa mongdb node也不太熟練
可以看我的github上面
https://github.com/boold/Small-code/tree/master/Small demo koa mongdb
更多專業前端知識,請上 【猿2048】www.mk2048.com
總結
以上是生活随笔為你收集整理的koa2 mongdb 做后端接口的小demo的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浮动层图片鼠标指针移到自动放大
- 下一篇: Json Schema的使用