阅读 642

使用Node+React实现简单CRUD

前言

这次使用react+antd+fetch写前端,node+express+mysql写后端,实现简单的react+node增删改查。

安装准备

react

// 安装 create-react-app 
cnpm install -g create-react-app 
// 创建 React 工程
create-react-app my-app 
// 进入工程目录
cd my-app 
// 启动 React
npm start
复制代码

依赖模块

cnpm install express body-parser --save
cnpm install antd --save
cnpm install mysql 
复制代码

后端

后端接口和之前基本一样,根据客户端传的参数,对数据库进行增删改查操作

// node 服务端

const userApi = require('./api/userApi');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

// 后端api路由
app.use('/api/user', userApi);

// 监听端口
app.listen(3000);
console.log('监听端口 :3000');
复制代码

前端

前端主要使用antdUI框架,完成数据的展示。

//引入的模块
import React, { Component } from 'react';
import './App.css';
import 'antd/dist/antd.css';
import { Table, Input, Modal, message,Popconfirm,  Divider,Button} from 'antd';
const Search = Input.Search;
class Fetch extends Component{
 constructor(props) {
   super(props)
   this.state = {
     allUsers: [],
     visible: false,
     user:"",
   }
   this.query = this.query.bind(this)
   this.delUser = this.delUser.bind(this)
   this.showModal = this.showModal.bind(this)
   this.handleName = this.handleName.bind(this)
   this.handleAge = this.handleAge.bind(this)
   this.handleAddress = this.handleAddress.bind(this)
   this.addUser = this.addUser.bind(this)
 }
//修改输入框内容触发事件
 handleName (e) {
   this.setState({
       username: e.target.value
   })
 }

 handleAge(e) {
   this.setState({
       userage: e.target.value
   })
 }

 handleAddress(e) {
   this.setState({
       useraddress: e.target.value
   })
 }
 //删除用户提示
success = () => {
   message.success('删除用户成功');
   this.queryAll() 
 };
 //增加用户提示,成功后清除数据
 addsuccess = () => {
   message.success('增加用户成功');
   this.queryAll() 
   this.refs.nameinput.state.value = "";
   this.refs.ageinput.state.value = "";
   this.refs.addinput.state.value = ""
 };

//弹窗
showModal = (record) => {
 this.setState({
   visible: true,
   userid:record.id,
   username:record.name,
   userage:record.age,
   useraddress:record.address
 });
}

handleOk = (e) => {
 console.log(e);
 this.setState({
   visible: false,
 });
}

handleCancel = (e) => {
 //console.log(e);
 this.setState({
   visible: false,
 });
}

...
 componentDidMount () {
 //组件加载完毕之后请求一次全部数据
   this.queryAll() 
 }

 render() {
   const columns = [ {
     title: 'Id',
     dataIndex: 'id',
     key: 'id',
   },
     {
     title: 'Name',
     dataIndex: 'name',
     key: 'name',
   }, {
     title: 'Age',
     dataIndex: 'age',
     key: 'age',
   }, {
     title: 'Address',
     dataIndex: 'address',
     key: 'address',
   },
    {
     title: 'Action',
     key: 'action',
     //数据修改,删除操作
     render: (text, record) => (
       <span>
         <span  onClick={() => this.showModal(record)}>
           <span className="oper">修改</span>
         </span>
         
         <Divider type="vertical" />
         
         <Popconfirm title="Sure to delete?" onConfirm={() => this.delUser(record.id)}>
             <span className="oper">Delete</span>
           </Popconfirm>
       </span>
     ),
   }];
   

   const data = this.state.allUsers
   return (
     <div className="fetchBox">
   
       <Search style={{width:500+"px"}}
     placeholder="input search text"
     onSearch={value => this.query(value)}
     enterButton
   />
       <Table  className="tableBox" columns={columns} dataSource={data} bordered={true} rowKey={record => record.id} />
//添加用户信息,根据ref获取dom的值,发给服务器
       <div className="addUser">
       <Input placeholder="姓名"  ref="nameinput"/>
       <Input placeholder="年龄"  ref="ageinput"/>
       <Input placeholder="地址"  ref="addinput"/>
       <Button   onClick={this.addUser.bind(this)}>Submit</Button> 
       </div>

       {/* 弹窗 */}

       <Modal
         title="修改用户信息"
         visible={this.state.visible}
         onOk={this.handleOk}
         onCancel={this.handleCancel}
       >
       //修改数据时根据用户ID显示修改前的信息
       <Input style={{marginBottom:20+"px"}}  value={this.state.username} onChange={this.handleName}/>
       <Input style={{marginBottom:20+"px"}} value={this.state.userage} onChange={this.handleAge}/>
       <Input  style={{marginBottom:20+"px"}}  value={this.state.useraddress}  onChange={this.handleAddress}/>
       <Button  style={{margin:0+"px"}}  onClick={this.modUser.bind(this)}>提交</Button> 
       </Modal>
     </div>
     
 )}
}
复制代码

fetch

原生fetch中一般用法为:
fetch(url,{
//配置
method:请求使用的方法,如:POST,GET,DELETE,UPDATE,PATCH 和 PUT
headers:请求头信息,可能是字符串,也有可能是Header对象
body:请求的body信息;post中传参位置
mode:请求模式:cors /no-cors/same-origin;
credentials:请求的credentials
cache:请求的cache模式:default,no-store,reload,no-cache,force-cache ,only-if-cached
})
.then((res)=>{})//定义响应类型
.then((res)=>{})// 显示响应类型 (数据本身)
.catch((res)=>{}); // 捕获错误

请求数据

//获取全部数据
 queryAll() {
   fetch( '/api/user/allUser',{
   headers: {
     'user-agent': 'Mozilla/4.0 MDN Example',
     'content-type': 'application/json'
   },
   method: 'GET', // *GET, POST, PUT, DELETE, etc.
   })
   .then((res) => {return res.json()})
   .then(data => {
   //  console.log(data)
     this.setState({allUsers: data})
   })
   .catch(e => console.log('错误:', e))
 }
//根据条件查询数据
 query(value) {
     //console.log(value)
     fetch( '/api/user/queryUser?params='+ value,{
     headers: {
       'user-agent': 'Mozilla/4.0 MDN Example',
       'content-type': 'application/json'
     },
     method: 'GET', // *GET, POST, PUT, DELETE, etc.
     })
     .then((response) => {
       return response.json();
       })
     .then(data => {
      // console.log(data)
       this.setState({allUsers: data})
     })
     .catch(e => console.log('错误:', e))
     }
复制代码

刚进入页面会进行一次数据的全部请求,查询功能根据条件查询数据,把数据在Table组件里展示

增加数据

//增加数据
 addUser(){
   var  username = this.refs.nameinput.state.value
   var  ageValue = this.refs.ageinput.state.value
   var addValue = this.refs.addinput.state.value
   console.log(username,ageValue,addValue)
   fetch( '/api/user/addUser',{
     headers: {
       'user-agent': 'Mozilla/4.0 MDN Example',
       'content-type': 'application/json'
     },
     body: JSON.stringify({ 
       username: username, 
       age:ageValue,
       address: addValue
     }), 
     method: 'POST', // *GET, POST, PUT, DELETE, etc.
     })
     .then((response) => {
       return response.json();
      })
       .then(data => {
         this.addsuccess()
       })
       .catch(e => console.log('错误:', e))
 }
复制代码

根据ref获取Input组件的值,把数据传给服务端,增加成功后给予提示,并清空输入框的值

删除数据

//删除数据
 delUser(key){
  // console.log(key)
   fetch( '/api/user/deleteUser?id='+ key,{
       headers: {'Content-Type': 'application/json'},
       method: 'DELETE', // *GET, POST, PUT, DELETE, etc.
     })
     .then((response) => {
       return response.json();
       })
     .then(data => {
       this.success()
     })
     .catch(e => console.log('错误:', e))
 }
复制代码

根据用户ID条件删除数据,删除成功后给予提示

修改数据

//修改数据

modUser(){
  var userid = this.state.userid
  var  username = this.state.username
  var  ageValue = this.state.userage
  var addValue = this.state.useraddress
  //console.log(username,ageValue,addValue)
  fetch( '/api/user/patchUser',{
    headers: {
      'user-agent': 'Mozilla/4.0 MDN Example',
      'content-type': 'application/json'
    },
    body: JSON.stringify({ 
      id:userid,
      username: username, 
      age:ageValue,
      address: addValue
    }), 
    method: 'PATCH', // *GET, POST, PUT, DELETE, etc.
    })
    .then((response) => {
      return response.json();
     })
      .then(data => {
       this.setState({
        visible: false,
      });
      this.queryAll() 
      })
      .catch(e => console.log('错误:', e))
}
复制代码

点击修改按钮,弹出修改提交数据框,默认展示已有信息,修改需要改的信息

跨域

在package.json中加上proxy代理配置