前端: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
新增編輯
刪除
一個簡單的使用者列表頁面,頂部有查詢,新增使用者按鈕,列表中有刪除,編輯使用者按鈕,底部有分頁。資料庫中使用者表設計
(一)前端搭建
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都是要與後端服務聯調的地方 (後面貼了完善版的前端)
(二)後端搭建
在後端的搭建中我用了koa 和 sequelize
資料庫 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;
});
複製程式碼
執行
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);
複製程式碼
總結: 我真的很厲害哦(不要臉)