koa2 mongdb 做后端接口的小demo
生活随笔
收集整理的這篇文章主要介紹了
koa2 mongdb 做后端接口的小demo
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
現(xiàn)在前端全棧里面有一種技術(shù)棧比較火
前端使用 vue 或者react 后端使用 koa2 mysql數(shù)據(jù)庫 或者mongdb做數(shù)據(jù)儲(chǔ)存
但是基本這樣的全棧教程 都要收費(fèi) 收費(fèi)就收費(fèi)吧 但是 有沒有遇到非常好的教程
于是 準(zhǔn)備硬著頭皮看別人項(xiàng)目的源碼 自己摸索 一步一步完成 koa mongdb的后端學(xué)習(xí)
下面就寫一個(gè)很簡單的koa mongdb 的數(shù)據(jù)庫寫入
user.js //這個(gè)頁面寫數(shù)據(jù)庫連接
var mongoose = require('mongoose') var Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/m_data') //m_data是我的數(shù)據(jù)庫名字 需要自己創(chuàng)建mongoose.connection.once('open',()=> {console.log("[mongoose]mongdb is start"); //監(jiān)聽啟動(dòng) })var userSchema = new Schema({ //建表username: {type: String},password: {type: String},call: {type: Number},email: {type: String} })var user = mongoose.model('User',userSchema); //返回另一個(gè)Model實(shí)例module.exports = user //導(dǎo)出data.js
let koa = require('koa') var mongoose = require('mongoose') let User = require('./user') //導(dǎo)入上一個(gè)頁面的數(shù)據(jù)庫模塊 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基礎(chǔ)的人來說 這應(yīng)該不難 稍微都能看懂 ,就是很簡單的數(shù)據(jù)庫寫入
假如你剛剛學(xué)習(xí)koa mongdb node也不太熟練
可以看我的github上面
https://github.com/boold/Small-code/tree/master/Small demo koa mongdb
更多專業(yè)前端知識(shí),請上 【猿2048】www.mk2048.com
總結(jié)
以上是生活随笔為你收集整理的koa2 mongdb 做后端接口的小demo的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浮动层图片鼠标指针移到自动放大
- 下一篇: Json Schema的使用