在上一章 React + MobX 入門及實例(一) 應用實例TodoList的基礎上html
npm install antd --save前端
npm install babel-plugin-import --save-devnode
{ "presets": ["react-native-stage-0/decorator-support"], "plugins": [ [ "import", { "libraryName": "antd", "style": true } ] ], "sourceMaps": true }
import { Button } from 'antd';
前提:mongodb的安裝與配置react
npm install --save express mongodb mongoosegit
引入body-parser中間件,做用是對post請求的請求體進行解析,轉換爲咱們須要的格式。
引入Promise異步,將多查詢分爲單個Promise,用Promise.all鏈接,待查詢完成後纔會發送查詢後的信息,若是不使用異步操做,查詢不會及時響應,前端請求的多是上一次的數據,這不是咱們想要的結果。github
//express const express = require('express'); const app = express(); //中間件 const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({extended: false}));// for parsing application/json app.use(bodyParser.json()); // for parsing application/x-www-form-urlencoded //mongoose const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/todolist',{useMongoClient:true}); mongoose.Promise = global.Promise; const db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function () { console.log("connect db.") }); //模型 const todos = mongoose.model('todos',{ key: Number, todo: String }); //發送json: 數據+數量 let sendjson = { data:[], count:0 }; //設置跨域訪問 app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1'); res.header("Content-Type", "application/json;charset=utf-8"); next(); }); //api/todos app.post('/api/todos', function(req, res){ const p1 = todos.find({}) .exec((err, result) => { if (err) console.log(err); else { sendjson['data'] = result; } }); const p2 = todos.count((err,result) => { if(err) console.log(err); else { sendjson['count'] = result; } }).exec(); Promise.all([p1,p2]) .then(function (result) { console.log(result); res.send(JSON.stringify(sendjson)); }); }); //api/todos/add app.post('/api/todos/add', function(req, res){ todos.create(req.body, function (err) { res.send(JSON.stringify({status: err? 0 : 1})); }) }); //api/todos/remove app.post('/api/todos/remove', function(req, res){ todos.remove(req.body, function (err) { res.send(JSON.stringify({status: err? 0 : 1})); }) }); //設置監聽80端口 app.listen(80, function () { console.log('listen *:80'); });
"scripts": { "start": "node scripts/start.js", "build": "node scripts/build.js", "test": "node scripts/test.js --env=jsdom", "server": "node server.js" },
Ⅲ. Fetch後臺數據
先後端交互使用fetch,也一樣寫在store裏,由action觸發。與後臺api一一對應,主要包含這三個部分:mongodb
@action fetchTodos(){ fetch('http://localhost/api/todos',{ method:'POST', headers: { "Content-type":"application/json" }, body: JSON.stringify({ current: this.current, pageSize: this.pageSize }) }) .then((response) => { // console.log(response); response.json().then(function(data){ console.log(data); this.total = data.count; this._key = data.data.length===0 ? 0: data.data[data.data.length-1].key; this.todos = data.data; this.loading = false; }.bind(this)); }) .catch((err) => { console.log(err); }) } @action fetchTodoAdd(){ fetch('http://localhost/api/todos/add',{ method:'POST', headers: { "Content-type":"application/json" }, body: JSON.stringify({ key: this._key, todo: this.newtodo, }) }) .then((response) => { // console.log(response); response.json().then(function(data){ console.log(data); /*成功添加 總數加1 添加失敗 最大_key恢復原有*/ if(data.status){ this.total += 1; this.todos.push({ key: this._key, todo: this.newtodo, }); message.success('添加成功!'); }else{ this._key -= 1; message.error('添加失敗!'); } }.bind(this)); }) .catch((err) => { console.log(err); }) } @action fetchTodoRemove(keyArr){ fetch('http://localhost/api/todos/remove',{ method:'POST', headers: { "Content-type":"application/json" }, body: JSON.stringify({ key: keyArr }) }) .then((response) => { console.log(response); response.json().then(function(data){ // console.log(data); if(data.status){ if(keyArr.length > 1) { this.todos = this.todos.filter(item => this.selectedRowKeys.indexOf(item.key) === -1); this.selectedRowKeys = []; }else{ this.todos = this.todos.filter(item => item.key !== keyArr[0]); } this.total -= keyArr.length; message.success('刪除成功!'); }else{ message.error('刪除失敗!'); } }.bind(this)); }) .catch((err) => { console.log(err); }) }
Githubexpress