使用Node+React實現簡單CRUD

前言

此次使用react+antd+fetch寫前端,node+express+mysql寫後端,實現簡單的react+node增刪改查。css

安裝準備

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框架,完成數據的展現。node

//引入的模塊
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)=>{}); // 捕獲錯誤mysql

請求數據

//獲取所有數據
 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組件裏展現react

增長數據

//增長數據
 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組件的值,把數據傳給服務端,增長成功後給予提示,並清空輸入框的值 sql

刪除數據

//刪除數據
 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))
}
複製代碼

點擊修改按鈕,彈出修改提交數據框,默認展現已有信息,修改須要改的信息express

跨域

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

相關文章
相關標籤/搜索