day23

1-使用 koa 搭建服务器

const koa = require('koa')

const app = new koa()

// 路由请求
// context  上下文  包含req和res
app.use(async (ctx)=>{
   ctx.body = 'hello koa2'
})

app.listen(3000)

 

2-如何配置 koa 路由

Koa 中的路由和 Express 有所不同,在 Express 中直接引入 Express 就可以配置路由,但是在 Koa 中我们需要安装对应的 koa-router 路由模块来实现

npm install koa-router

 

const koa = require('koa')
const router = require('koa-router')() // 引入和实例化路由

const app = new koa() // 创建koa实列

// 配置路由
//ctx 上下文(content),包含了request和response信息
router.get('/', async (ctx, next) => {
  ctx.body="Hello koa";
})

router.get('/news', async (ctx, next) => {
  ctx.body="新闻 page"
});
app.use(router.routes()); //作用:启动路由

// 作用: 这是官方文档的推荐用法,我们可以 看到 router.allowedMethods()用在了路由匹配 router.routes()之后
// 所以在当所有 路由中间件最后调用.此时根据 ctx.status 设置 response 响应头
app.use(router.allowedMethods()); // 可以不配置这个,建议配置上

app.listen(3000,()=>{
  console.log('starting at port 3000');
})

3-静态资源如何获取

const koa = require('koa')
const app = new koa()

const router = require('koa-router')()

// 加载
const static = require('koa-static')
const path = require('path')

// 获取静态资源
app.use(static(path.join(__dirname,'public')))


// 启用路由
app.use(router.routes())
  .use(router.allowedMethods())


app.listen(3000)

4-koa 如何使用模板引擎

在node中使用模板引擎需要一个中间件koa-views

在koa中使用ejs

安装模块

# 安装koa模板使用中间件
npm install --save koa-views

# 安装ejs模板引擎
npm install --save ejs

 

5-使用 koa 实现一个用户增删改查的案例

搭建前端页面

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);

后端搭建

在后端的搭建中我用了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.js

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.js

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.用户表

根据表设计

 

 

/server/model/user.js

sequelize 点击可看使用方式

/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目录内。

/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;
});
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);
posted @ 2021-03-07 22:12  雨辰~  阅读(56)  评论(0)    收藏  举报