本文將介紹如何使用react+koa+MongoDB開發一個簡單的頁面,並寫幾個簡單的接口來實現對數據庫的增刪改查。css
我的比較喜歡用docker來啓動MongoDB。
因此先去docker官網下載一個docker。www.docker.com/products/do…
docker啓動mongoDb前端
docker run --name mongo -p 27017:27017 -d mongo:3.4
// —name 指定庫的名字,若是不指定會使用一串隨機字符串。
// -p 27017:27017 官方的鏡像已經暴露了 27017 端口,咱們將它映射到主機的端口上。
// -d 在後臺運行。
// mongo:3.4 指定鏡像版本,默認是 latest 。建議老是本身指定版本。
docker ps
// 查看正在運行的容器
複製代碼
docker exec -it mongo mongo
use newdb
db.user.insert({name: 'Brady'})
複製代碼
建立一個my-server文件夾,底下目錄結構以下node
const Koa = require('koa')
const cors = require('koa-cors')
const app = new Koa()
const router = require('./router')
const bodyParser = require('koa-bodyparser')
app.use(bodyParser()) // 把koa2上下文的formData數據解析到ctx.request.body中
app.use(cors()) // 解決跨域問題
app.use(router.routes()) // 使用路由中間件處理路由
app.listen(3366) // 監聽3366端口
console.log('app is stared & listening on port 3366')
複製代碼
router.js
劃分路由react
const router = require('koa-router')()
const UserController = require('./controller/UserController')
router.get('/user/getUser', UserController.getUser) // 獲取用戶名字的接口
router.post('/user/updateUser', UserController.updateUser) // 修改用戶名字接口
module.exports = router
複製代碼
/controller/UserController.js
編寫具體的接口邏輯ios
const { User } = require("../model/");
class UserController {
static async getUser(ctx) {
const { id } = ctx.request.query;
const list = await User.getUser(id);
ctx.body = list;
}
static async updateUser(ctx) {
const { name, id } = ctx.request.body;
const result = await User.update({ _id: id }, { name });
ctx.body = {
code: 0,
message: "success"
};
}
}
module.exports = UserController;
複製代碼
/model/index.js
將文件夾中的model導出mongodb
const fs = require('fs')
const path = require('path')
// 將文件夾中的model導出
const models = fs.readdirSync(path.resolve(__dirname, './'))
let ret = {}
for (const model of models) {
if (model === 'index.js' || model === 'ModelBuilder.js') {
continue
}
ret[model.slice(0, model.indexOf('.js'))] = require(`./${model}`)
}
module.exports = ret
複製代碼
/model/ModelBuilder.js
model的構造工廠docker
const mongoose = require('mongoose')
class ModelBuilder {
/**
* 構造model
*
* @param.name {String} collection name
* @param.db {String} db name
* @param.attributes {Object} 表字段定義
* @param.statics {Object} 靜態方法
* @param.methods {Object} instance methods
*/
static build ({name = '', db = 'newdb', attributes = {}, statics = {}, methods = {}}) {
const schema = new mongoose.Schema(attributes)
schema.set('timestamps', true)
schema.set('minimize', false)
schema.set('collection', name)
schema.set('strict', false)
schema.set('id', true)
schema.set('toObject', {getters: true, virtuals: true, minimize: false, id: true})
schema.set('toJSON', {getters: true, virtuals: true, minimize: false, id: true})
schema.statics = statics
schema.methods = methods
const connection = mongoose.createConnection('mongodb://localhost:27017/' + db)
const model = connection.model(name, schema)
model.ObjectId = mongoose.Types.ObjectId
return model
}
}
module.exports = ModelBuilder
複製代碼
/model/User.js
數據庫裏具體某一張表的數據結構和靜態方法定義shell
const ModelBuilder = require('./ModelBuilder.js')
module.exports = ModelBuilder.build({
name: 'user',
attributes: {
name: {type: String}
},
statics: {
/**
* 取某個用戶
*/
async getUser (userId) {
let user = await this.findById(userId)
if (!user) {
throw new Error('error')
}
return user
}
}
})
複製代碼
package.json
項目的依賴和啓動項目的命令數據庫
{
"name": "backend",
"version": "1.0.0",
"description": "backend",
"main": "app.js",
"scripts": {
"dev": "nodemon -w ./ app.js"
},
"keywords": [
"koa2"
],
"author": "Brady",
"license": "ISC",
"dependencies": {
"koa": "^2.4.1",
"koa-bodyparser": "^3.2.0",
"koa-cors": "0.0.16",
"koa-router": "^7.3.0",
"mongoose": "^4.13.6",
"nodemon": "^1.12.1"
}
}
複製代碼
在項目中打開命令行,輸入npm
npm run dev
複製代碼
而後後端服務就跑起來了
爲了方便,就直接使用react推薦的create-react-app來新建一個react項目
打開命令行
npm i -g create-react-app
create-react-app my-app
cd my-app
npm i
npm start
複製代碼
輸入以上命令後瀏覽器就會出現這樣的一個頁面了
import React, { Component } from "react";
import "./App.css";
import axios from "axios";
class App extends Component {
constructor() {
super();
this.state = {
name: "",
value: ""
};
}
componentDidMount() {
this.getName();
}
getName = async () => {
let { data } = await axios.get(`http://localhost:3366/user/getUser`, {
params: { id: "5be0eb13b3674cac694c7abf" }
});
this.setState({ name: data.name });
};
editName = async () => {
await axios.post(`http://localhost:3366/user/updateUser`, {
id: "5be0eb13b3674cac694c7abf",
name: this.state.value
});
};
render() {
return (
<div className="App">
<header className="App-header">
<p>hello {this.state.name}</p>
<p>
修更名字:{" "}
<input
type="text"
value={this.state.value}
onChange={e => {
this.setState({ value: e.currentTarget.value });
}}
/>
</p>
<div
className="btn"
onClick={async () => {
await this.editName();
this.getName()
}}
>
肯定
</div>
</header>
</div>
);
}
}
export default App;
複製代碼
而後在項目中打開命令行
npm i axios
複製代碼
最後就會在瀏覽器看到
到此爲止,已經介紹瞭如何建立一個網頁並實現增、查、改數據庫。接下來要作什麼功能就能夠自由發揮,天馬星空了。