一個簡單的Node-React-Koa用戶管理增刪改查小demo

前端:create-react-app antd axios react

後端:node koa sequelize mysql

做爲一個前端小新手,在嘗試了一段時間的react前端工做後,就想嘗試用node編寫web服務,僞裝本身很厲害。在看了一段時間的node教程+express教程+koa教程等,就開始準備本身寫一個小demo。

前端效果圖(react+ antd + create-react-app)

github地址: node-react-koa

添加編輯css

刪除 html

一個簡單的用戶列表頁面,頂部有查詢,添加用戶按鈕,列表中有刪除,編輯用戶按鈕,底部有分頁。

數據庫中用戶表設計

(一)前端搭建

1.用facebook官方開發的create-react-app 腳手架搭建一個react前端框架。

(1)全局安裝 create-react-app

npm install -g create-react-app
複製代碼

(2)建立項目

create-react-app node-react-koa
cd node-react-koa && mkdir server //node服務都放在該文件下
npm run eject //可省略,只爲了看配置 config
npm start
複製代碼

自此項目目錄以下圖

(3) 搭建前端頁面

1.安裝antd ,開箱即用的高質量 React 組件。antd design
npm install antd --save 
複製代碼
2.安裝axios 一個基於 promise 的 HTTP 庫,能夠用在瀏覽器和 node.js 中
npm install axios --save
複製代碼
由於是一個小demo,所以我直接在 src/App.js 中直接畫頁面。
src/App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
import { Table, Pagination, Input, Row, Button, Modal, Form } from 'antd';
import 'antd/dist/antd.css'
const { Search } = Input;
const FormItem = Form.Item;
const { confirm } = Modal;
class App extends Component {
  constructor(props) {
    super(props);
  }
  columns = [{
    dataIndex: "username", title: "用戶",
  }, {
    dataIndex: "age", title: "年齡",
  }, {
    dataIndex: "address", title: "地址"
  }, {
    dataIndex: "action", title: "操做", width: 200, render: (text, row) => {
      return <div>
        <Button onClick={() => this.modal('edit', row)} >編輯</Button>
        <Button style={{ marginLeft: 10 }} type="danger" onClick={() => this.remove(row)} >刪除</Button>
      </div>
    }
  }];
  state = {
    dataSource: [{ username: "slf", age: "18", address: "杭州", id: 1 }],
    current: 1,
    size: 10,
    total: 1,
    visible: false,
    modalType: "add"
  }
  componentDidMount() {
    this.sizeChange(this.state.current,this.state.size);
  }
  //分頁
  sizeChange = (current, size) => {
  //todo
  }
  //提交
  handleOk = () => {
  //todo 
  }
  //添加編輯用戶
  modal = (type, row) => {
    this.setState({
      visible: true,
      modalType: type
    }, () => {
      this.props.form.resetFields();
      if (type === 'add') return;
      this.props.form.setFieldsValue({
        username: row.username,
        age: row.age,
        address: row.address
      })
    })
  }
  remove = (row) => {
    confirm({
      title: '是否要刪除該用戶?',
      okText: '是',
      okType: '否',
      cancelText: 'No',
      onOk() {
        //todo
      },
      onCancel() {
        //todo
      },
    });
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    return (
      <div className="App">
        <Row>
          <Search style={{ width: 300 }} />
          <Button type="primary" style={{ marginLeft: 20 }} onClick={() => this.modal('add')} >添加用戶</Button>
        </Row>
        <Row style={{ paddingTop: 20 }}>
          <Table dataSource={this.state.dataSource} rowKey={row => row.id} bordered columns={this.columns} pagination={false} />
        </Row>
        <Row style={{ paddingTop: 20 }}>
          <Pagination
            showTotal={(total) => `共 ${total} 條`}
            current={this.state.current} total={this.state.total} pageSize={this.state.size}
            onChange={this.sizeChange} />
        </Row>
        <Modal
          title={this.state.modalType === 'add' ? "添加用戶" : "編輯用戶"}
          onOk={this.handleOk}
          onCancel={() => this.setState({ visible: false })}
          visible={this.state.visible}
        >
          <Form>
            <FormItem label="用戶"  {...formItemLayout}>
              {getFieldDecorator('username', {
                rules: [{ required: true, message: 'Please input your username!' }],
              })(
                <Input placeholder="Username" />
              )}
            </FormItem>
            <FormItem label="年齡"  {...formItemLayout}>
              {getFieldDecorator('age', {
                rules: [{ required: true, message: 'Please input your age!' }],
              })(
                <Input placeholder="age" />
              )}
            </FormItem>
            <FormItem label="地址"  {...formItemLayout}>
              {getFieldDecorator('address', {
                rules: [{ required: true, message: 'Please input your address!' }],
              })(
                <Input placeholder="address" />
              )}
            </FormItem>
          </Form>
        </Modal>
      </div >
    );
  }
}
export default Form.create()(App);
複製代碼
上面代碼中的todo都是要與後端服務聯調的地方 (後面貼了完善版的前端)

(二)後端搭建

在後端的搭建中我用了koasequelize

數據庫 mysql

koa -- 基於 Node.js 平臺的下一代 web 開發框架

Sequelize -- 是JS端的hibernate,完成server端到數據庫的CRUD等等操做。

1.安裝依賴

npm install koa koa-body koa-cors koa-router sequelize mysql2 --save
複製代碼
koa-body 由於Web應用離不開處理表單(例如用戶的添加編輯表單)。本質上,表單就是 POST 方法發送到服務器的鍵值對。koa-body模塊能夠用來從 POST 請求的數據體裏面提取鍵值對。
koa-cors 解決跨域問題
koa-router url處理器映射

2.準備工做

在server目錄下面新建如下內容:前端

/server/app.js 爲運行文件 運行方式 node server/app.js
/server/routers 前端訪問api路徑
/server/model 數據層: index.js 數據庫鏈接 user.js 用戶表

3.新建koa服務

/server/app.jsnode

const Koa = require('koa');
const cors = require('koa-cors');
const router = require('./routers/index')
// 建立一個Koa對象表示web app自己:
const app = new Koa();
app.use(cors());//解決跨域問題
// 對於任何請求,app將調用該異步函數處理請求:
app.use(async (ctx, next) => {
    console.log(ctx.request.path + ':' + ctx.request.method);
    await next();
});
app.use(router.routes());
app.listen(3005);
console.log('app started at port 3005...');
複製代碼

4.鏈接數據庫

/server/model/index.jsmysql

operatorsAliases必定要寫true,不然後續使用sql會用問題,例如使用$like模糊查詢會出現Invalid value問題
const Sequelize = require('sequelize');
const sequelize = new Sequelize('數據庫名', '用戶名', '密碼', {
    host: 'localhost',
    dialect: 'mysql',
    operatorsAliases: true,
    pool: {
        max: 5, min: 0, acquire: 30000, idle: 10000
    },
    define: {
        timestamps: false,
    },
})
sequelize
    .authenticate()
    .then(() => {
        console.log('Connection has been established successfully.');
    })
    .catch(err => {
        console.error('Unable to connect to the database:', err);
    });
module.exports = sequelize;
複製代碼

5.用戶表

根據表設計react

/server/model/user.jsios

sequelize 點擊可看使用方式git

/server/model/user.js

const Sequelize = require('sequelize')
const sequelize = require('./index')
const User = sequelize.define('userinfos', {
    id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true, unique: true },
    username: { type: Sequelize.STRING },
    age:{type:Sequelize.INTEGER},
    address: { type: Sequelize.STRING },
    isdelete: { type: Sequelize.INTEGER, allowNull: true }//軟刪除 0爲未刪除,1爲刪除
});
module.exports = User;
複製代碼

下面重點來了,本文重點,寫server!!!!!

由於項目小,我就寫在了routers目錄內。github

/routers/index.js
複製代碼

1.引入要用的koa-body, koa-router ,數據表(model/user.js)

const koaBody = require('koa-body');
const router = require('koa-router')();
const User = require('../model/user');
複製代碼

2.第一個api接口:獲取全部的用戶列表

router.get('/users', async (ctx, next) => {
    const user = await User.findAll({
        where: { isdelete: 0 },
    })
    ctx.body = user;
});
複製代碼

運行web

node server/app.js
複製代碼

postman 測試

成功!

下面開始正式的增刪改查。

1.增長用戶 先回到src/App.js,完善添加提交方法

handleOk = () => {
        this.props.form.validateFieldsAndScroll((err, value) => {
            if (err) return;
            let data = {
                username: value.username, age: value.age, address: value.address
            };
            if (this.state.modalType === 'add') {
                axios.post("http://127.0.0.1:3005/user", data)
                    .then(msg => {
                        this.sizeChange(this.state.current, this.state.size);
                        this.setState({visible: false});
                        message.success('success!')
                    })
            } else {
                axios.put("http://127.0.0.1:3005/user/" + this.state.editRow.id, data)
                    .then(data => {
                        this.sizeChange(this.state.current, this.state.size);
                        this.setState({visible: false});
                        message.success('success!')
                    })
            }
        })
    }
複製代碼

2.添加api server/routers/index.js

router.post('/user', koaBody(), async (ctx) => {
    const user = await User.build(ctx.request.body).save();
    ctx.body = user;
})
複製代碼

3.同理編輯用戶 server/routers/index.js

router.put('/user/:id', koaBody(), async (ctx) => {
    const body = ctx.request.body;
    const user = await User.findById(ctx.params.id);
    await user.update({...body})
    ctx.body = user;
})
複製代碼

4.刪除用戶 server/router/index.js

router.delete('/user/:id', async (ctx) => {
    const user = await User.findById(ctx.params.id).then((user) => user);
    user.isdelete = 1;
    await user.save();
    ctx.body = { success: true }
})
複製代碼

5.分頁查詢 server/router/index.js

//{"limit":10,"offset":0,"search":"slf"}
router.post('/user-search', koaBody(), async (ctx) => {
    const body = ctx.request.body;
    const user = await User.findAndCount({
        where: {
            isdelete: 0, username: {
                $like: `%${body.search}%`
            }
        },
        limit: body.limit,
        offset: body.offset
    });
    ctx.body = user;
});
複製代碼

最後

module.exports = router;
複製代碼

完善版前端

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
import {Table, Pagination, Input, Row, Button, Modal, Form, message} from 'antd';
import 'antd/dist/antd.css'

const {Search} = Input;
const FormItem = Form.Item;
const {confirm} = Modal;

class App extends Component {
    constructor(props) {
        super(props);
    }

    columns = [{
        dataIndex: "username", title: "用戶",
    }, {
        dataIndex: "age", title: "年齡",
    }, {
        dataIndex: "address", title: "地址"
    }, {
        dataIndex: "action", title: "操做", width: 200, render: (text, row) => {
            return <div>
                <Button onClick={() => this.modal('edit', row)}>編輯</Button>
                <Button style={{marginLeft: 10}} type="danger" onClick={() => this.remove(row)}>刪除</Button>
            </div>
        }
    }];
    state = {
        dataSource: [],
        current: 1,
        size: 10,
        total: 0,
        visible: false,
        modalType: "add",
        search: "",
        editRow: {}
    }

    componentDidMount() {
        this.sizeChange(this.state.current, this.state.size);
    }

    //分頁
    sizeChange = (current, size) => {
        let data = {
            search: this.state.search,
            limit: size,
            offset: (parseInt(current) - 1) * size
        }
        axios.post("http://localhost:3005/user-search", data).then(data => {
            this.setState({
                dataSource: data.data.rows,
                total: data.data.count,
                current, size
            })
        })
    };
    //提交
    handleOk = () => {
        this.props.form.validateFieldsAndScroll((err, value) => {
            if (err) return;
            let data = {
                username: value.username, age: value.age, address: value.address
            };
            if (this.state.modalType === 'add') {
                axios.post("http://127.0.0.1:3005/user", data)
                    .then(msg => {
                        this.sizeChange(this.state.current, this.state.size);
                        this.setState({visible: false});
                        message.success('success!')
                    })
            } else {
                axios.put("http://127.0.0.1:3005/user/" + this.state.editRow.id, data)
                    .then(data => {
                        this.sizeChange(this.state.current, this.state.size);
                        this.setState({visible: false});
                        message.success('success!')
                    })
            }
        })
    }
    //添加編輯用戶
    modal = (type, row) => {
        this.setState({
            visible: true,
            modalType: type
        }, () => {
            this.props.form.resetFields();
            if (type === 'add') return;
            this.props.form.setFieldsValue({
                username: row.username,
                age: row.age,
                address: row.address
            })
            this.setState({editRow: row})
        })
    }
    remove = (row) => {
        let _this = this;
        confirm({
            title: '是否要刪除該用戶?',
            okText: '是',
            okType: '否',
            cancelText: 'No',
            onOk() {
                axios.delete("http://127.0.0.1:3005/user/"+row.id)
                    .then(data=>{
                        _this.sizeChange(_this.state.current, _this.state.size);
                        message.success('success!')
                    })
            }
        });
    };
    search = (name) => {
        this.setState({
            search: name
        }, () => {
            this.sizeChange(1, 10)
        })
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 4},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 16},
            },
        };
        return (
            <div className="App">
                <Row>
                    <Search style={{width: 300}} onChange={this.search}/>
                    <Button type="primary" style={{marginLeft: 20}} onClick={() => this.modal('add')}>添加用戶</Button>
                </Row>
                <Row style={{paddingTop: 20}}>
                    <Table dataSource={this.state.dataSource} rowKey={row => row.id} bordered columns={this.columns}
                           pagination={false}/>
                </Row>
                <Row style={{paddingTop: 20}}>
                    <Pagination
                        showTotal={(total) => `共 ${total} 條`}
                        current={this.state.current} total={this.state.total} pageSize={this.state.size}
                        onChange={this.sizeChange}/>
                </Row>
                <Modal
                    title={this.state.modalType === 'add' ? "添加用戶" : "編輯用戶"}
                    onOk={this.handleOk}
                    onCancel={() => this.setState({visible: false})}
                    visible={this.state.visible}
                >
                    <Form>
                        <FormItem label="用戶"  {...formItemLayout}>
                            {getFieldDecorator('username', {
                                rules: [{required: true, message: 'Please input your username!'}],
                            })(
                                <Input placeholder="username"/>
                            )}
                        </FormItem>
                        <FormItem label="年齡"  {...formItemLayout}>
                            {getFieldDecorator('age', {
                                rules: [{required: true, message: 'Please input your age!'}],
                            })(
                                <Input placeholder="age"/>
                            )}
                        </FormItem>
                        <FormItem label="地址"  {...formItemLayout}>
                            {getFieldDecorator('address', {
                                rules: [{required: true, message: 'Please input your address!'}],
                            })(
                                <Input placeholder="address"/>
                            )}
                        </FormItem>
                    </Form>
                </Modal>
            </div>
        );
    }
}

export default Form.create()(App);

複製代碼

總結: 我真的很厲害哦(不要臉)

相關文章
相關標籤/搜索