React Ant Design+Node.js Express+Mysql實現後端分頁(帶富文字編輯器)
阿新 • • 發佈:2021-01-12
home.jsx:
import React, { Component } from 'react' import { Table, Card, Modal, Button, Form, Input, Select, notification } from 'antd' import axios from 'axios' import qs from 'qs' import { PlusOutlined, MinusOutlined } from '@ant-design/icons'; // react-draft-wysiwyg begin import { EditorState, convertToRaw, ContentState } from 'draft-js'; import { Editor } from'react-draft-wysiwyg'; import draftToHtml from 'draftjs-to-html'; import htmlToDraft from 'html-to-draftjs'; import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css' import './react-draft-wysiwyg.less' // react-draft-wysiwyg end const layout = { labelCol: { span: 3, }, wrapperCol: { span:19, } }; export default class Home extends Component { state = { showRichText: false, // react-draft-wysiwyg editorContent: '', // react-draft-wysiwyg editorState: '', // react-draft-wysiwyg selectedRowKeys: [], // 表格選擇項Keys selectedRows: [], // 表格選擇項Rows tableData: [], total:0, // for Pagination columns: [ { title: 'ID', dataIndex: 'id', width: 30, }, { title: '標題', dataIndex: 'title', width: 500, render: (text, record) => <a href="javascript: void(0)" target="_self" onClick={() => this.handleShowDetailBlog(record.id)}>{text}</a> }, { title: '內容', dataIndex: 'content' }, ], addModalVisible: false, showBlogModalVisible: false, blogDetail: '' }; /** * * @react-draft-wysiwyg begin */ handleClearContent = () => { this.setState({ editorState: '' }) } handleGetText = () => { this.setState({ showRichText: true }) } onEditorChange = (editorContent) => { this.setState({ editorContent, }); }; onEditorStateChange = (editorState) => { this.setState({ editorState }); }; // @react-draft-wysiwyg end onTableSelectChange = (selectedRowKeys, selectedRows) => { console.log('selectedRowKeys changed: ', selectedRowKeys); console.log('selectedRows changed: ', selectedRows); this.setState({ selectedRowKeys, selectedRows }); }; onSelectChange = selectedRowKeys => { console.log('selectedRowKeys changed: ', selectedRowKeys); this.setState({ selectedRowKeys }); }; /** * 表格 */ // 獲取表格資料 getData(pageNumber, pageSize) { axios.get(`http://localhost:5555/api/blog_list/?pageSize=${pageSize}&pageNumber=${pageNumber}&sortName=id&sortOrder=desc&_=1595230808893`).then((resp) => { let ajaxData = []; for (let i = 0; i < resp.data.rows.length; i++) { ajaxData.push({ key: resp.data.rows[i].id, id: resp.data.rows[i].id, title: resp.data.rows[i].title, content: resp.data.rows[i].content, }); } this.setState({ tableData: ajaxData, total: resp.data.total }) }, (err) => { console.log(err); }); } onChange = (pageNumber, pageSize) => { this.pageNum = pageNumber; this.pageSize = pageSize; this.getData(pageNumber, pageSize); }; /** * 新增modal */ // for modal showAddModal = () => { this.setState({ addModalVisible: true }) } addModalHandleOk = e => { const _this = this; this.addModalFormRef.current.validateFields() .then(values => { console.log(this.state.editorContent); const params = { title: values.title, content: draftToHtml(convertToRaw(this.state.editorState.getCurrentContent())) }; axios.post(`http://localhost:5555/api/add_blog`, qs.stringify(params)).then((resp) => { if (resp.ret) { console.log(resp.msg); } else { this.addModalFormRef.current.resetFields(); this.setState({ editorState: '', addModalVisible: false }); this.pageNum = 1; this.getData(this.pageNum, this.pageSize); } }, (err) => { console.log(err); }); }) .catch(info => { console.log('Validate Failed:', info); }); } addModalHandCancel = e => { this.addModalFormRef.current.resetFields(); this.setState({ addModalVisible: false }) } /** * 刪除blog */ onDeleteAdministrators = () => { let len = this.state.selectedRowKeys.length; if (len === 0) { notification['error']({ message: '錯誤提示', description: '請選擇要刪除的文章!', }) } else { const params = { idArr: JSON.stringify(this.state.selectedRowKeys) } const _this = this; axios.post(`http://localhost:5555/api/delete_blogs`, qs.stringify(params)).then((resp) => { if (resp.data.ret) { notification['success']({ message: '成功提示', description: resp.data.msg, }) this.pageNum = 1; _this.getData(this.pageNum, this.pageSize); } else { notification['error']({ message: '錯誤提示', description: resp.data.msg, }) } }, (err) => { notification['error']({ message: '錯誤提示', description: '網路錯誤,刪除失敗!' }) }); } } // 表單相關 addModalFormRef = React.createRef(); // 定義一個表單 /** * 顯示blog Modal */ handleShowDetailBlog = (id) => { axios.get(`http://localhost:5555/api/get_blog_detail?id=${id}`, {}).then((resp) => { const contentBlock = htmlToDraft(resp.data.content); const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks); const editorState = EditorState.createWithContent(contentState); console.log("contentState:"); console.log(contentState); if (resp.data.ret) { this.setState({ showBlogModalVisible: true, blogDetail: resp.data.content }) } else { } }, (err) => { console.log(err); }); } handleShowBlogModalHandleOk = () => { this.setState({ showBlogModalVisible: false }) } handleShowBlogModalHandleCancel = () => { this.setState({ showBlogModalVisible: false }) } /** * 鉤子函式 */ componentDidMount() { this.getData(1, 10); } render() { // 控制表格選擇 const rowSelection = { selectedRowKeys: this.state.selectedRowKeys, onChange: this.onTableSelectChange }; return (<> <Card title="部落格列表" extra={<span><Button type="primary" ghost size="small" icon={<PlusOutlined />} style={{ marginRight: 15 }} onClick={this.showAddModal}>新增</Button><Button type="primary" ghost size="small" icon={<MinusOutlined />} onClick={() => { this.onDeleteAdministrators() }}>刪除</Button></span>} style={{ width: '100%' }}> <Table onRow={record => { return { onClick: event => { console.log(record) }, // 點選行 onDoubleClick: event => { }, onContextMenu: event => { }, onMouseEnter: event => { }, // 滑鼠移入行 onMouseLeave: event => { }, }; }} rowSelection={rowSelection} columns={this.state.columns} dataSource={this.state.tableData} pagination={{ current: this.pageNum, total: this.state.total, pageSizeOptions: [5, 10, 20, 50, 100], defaultPageSize: 10, showSizeChanger: true, showQuickJumper: true, showTotal: (total, range) => `共 ${total} 條`, onChange: this.onChange }} bordered > </Table> <Modal title="建立" visible={this.state.addModalVisible} width={800} onOk={this.addModalHandleOk} onCancel={this.addModalHandCancel} okText="確認" cancelText="取消" maskClosable={false} destroyOnClose={true} > <Form {...layout} ref={this.addModalFormRef} name="control-ref" preserve={false}> <Form.Item label="標題" style={{ marginBottom: 0 }}> <Form.Item name="title" style={{ display: 'inline-block', width: 'calc(100% - 8px)', marginRight: 15 }} rules={[ { required: true, message: "標題不能為空" } ]} > <Input /> </Form.Item> </Form.Item> <Form.Item label="內容" style={{ marginBottom: 0 }}> <Form.Item name="content" style={{ display: 'inline-block', width: 'calc(100% - 8px)' }} rules={[ { required: true, message: "內容不能為空" } ]} > <Editor editorState={this.state.editorState} wrapperClassName="demo-wrapper" editorClassName="demo-editor" onEditorStateChange={this.onEditorStateChange} /> {/* <TextArea rows={4} /> */} </Form.Item> </Form.Item> </Form> </Modal> <Modal title="詳情" visible={this.state.showBlogModalVisible} width={800} onOk={this.handleShowBlogModalHandleOk} onCancel={this.handleShowBlogModalHandleCancel} okText="確定" cancelText="取消" maskClosable={false} destroyOnClose={true} footer={null} > <div dangerouslySetInnerHTML={{ __html: this.state.blogDetail }} style={{ height: 400, overflow: 'auto' }} /> </Modal> </Card> </> ) } }
package.json:
{ "name": "antd-demo", "version": "0.1.0", "private": true, "dependencies": { "@ant-design/icons": "^4.2.1", "@babel/core": "7.9.0", "@svgr/webpack": "4.3.3", "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "@tinymce/tinymce-react": "^3.8.4", "@typescript-eslint/eslint-plugin": "^2.10.0", "@typescript-eslint/parser": "^2.10.0", "antd": "^4.7.0", "axios": "^0.19.2", "babel-eslint": "10.1.0", "babel-jest": "^24.9.0", "babel-loader": "8.1.0", "babel-plugin-import": "^1.13.0", "babel-plugin-named-asset-import": "^0.3.6", "babel-preset-react-app": "^9.1.2", "camelcase": "^5.3.1", "case-sensitive-paths-webpack-plugin": "2.3.0", "css-loader": "3.4.2", "dotenv": "8.2.0", "dotenv-expand": "5.1.0", "draft-js": "^0.11.7", "draftjs-to-html": "^0.9.1", "echarts": "^4.9.0", "echarts-for-react": "^2.0.16", "eslint": "^6.6.0", "eslint-config-react-app": "^5.2.1", "eslint-loader": "3.0.3", "eslint-plugin-flowtype": "4.6.0", "eslint-plugin-import": "2.20.1", "eslint-plugin-jsx-a11y": "6.2.3", "eslint-plugin-react": "7.19.0", "eslint-plugin-react-hooks": "^1.6.1", "file-loader": "4.3.0", "fs-extra": "^8.1.0", "html-to-draftjs": "^1.5.0", "html-webpack-plugin": "4.0.0-beta.11", "identity-obj-proxy": "3.0.0", "jest": "24.9.0", "jest-environment-jsdom-fourteen": "1.0.1", "jest-resolve": "24.9.0", "jest-watch-typeahead": "0.4.2", "mini-css-extract-plugin": "0.9.0", "optimize-css-assets-webpack-plugin": "5.0.3", "pnp-webpack-plugin": "1.6.4", "postcss-flexbugs-fixes": "4.1.0", "postcss-loader": "3.0.0", "postcss-normalize": "8.0.1", "postcss-preset-env": "6.7.0", "postcss-safe-parser": "4.0.1", "qs": "^6.9.4", "react": "^16.13.1", "react-app-polyfill": "^1.0.6", "react-dev-utils": "^10.2.1", "react-dom": "^16.13.1", "react-draft-wysiwyg": "^1.14.5", "react-router": "^4.2.0", "react-router-dom": "^4.2.0", "react-transition-group": "^4.4.1", "redux": "^4.0.5", "resolve": "1.15.0", "resolve-url-loader": "3.1.1", "sass-loader": "8.0.2", "semver": "6.3.0", "style-loader": "0.23.1", "terser-webpack-plugin": "2.3.5", "ts-pnp": "1.1.6", "url-loader": "2.3.0", "webpack": "4.42.0", "webpack-dev-server": "3.10.3", "webpack-manifest-plugin": "2.2.0", "workbox-webpack-plugin": "4.3.1" }, "scripts": { "start": "node scripts/start.js", "build": "node scripts/build.js", "test": "node scripts/test.js" }, "eslintConfig": { "extends": "react-app" }, "proxy": "http://localhost:9999", "homepage": ".", "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "jest": { "roots": [ "<rootDir>/src" ], "collectCoverageFrom": [ "src/**/*.{js,jsx,ts,tsx}", "!src/**/*.d.ts" ], "setupFiles": [ "react-app-polyfill/jsdom" ], "setupFilesAfterEnv": [ "<rootDir>/src/setupTests.js" ], "testMatch": [ "<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}", "<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}" ], "testEnvironment": "jest-environment-jsdom-fourteen", "transform": { "^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest", "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js", "^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js" }, "transformIgnorePatterns": [ "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$", "^.+\\.module\\.(css|sass|scss)$" ], "modulePaths": [], "moduleNameMapper": { "^react-native$": "react-native-web", "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy" }, "moduleFileExtensions": [ "web.js", "js", "web.ts", "ts", "web.tsx", "tsx", "json", "web.jsx", "jsx", "node" ], "watchPlugins": [ "jest-watch-typeahead/filename", "jest-watch-typeahead/testname" ] }, "devDependencies": { "less": "^3.12.2", "less-loader": "^6.2.0" } }
Expressmain.js:
const express = require("express") const fs = require("fs") const mysql = require("mysql") const util = require("util") const {getNow} = require("./tool") const app = express(); const bodyParser = require("body-parser"); const { nextTick } = require("process"); app.use("/static/", express.static("./static/")); app.use('/node_modules/', express.static('./node_modules/')); app.engine("html", require("express-art-template")) app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '12345678', database: 'react-ts-blog' }); connection.connect(); // 獲取所有資料 app.get("/api/blog_list", (req, res) => { let obj = { ret: false, total: 0, rows: [], msg: "" } const pageSize = Number(req.query.pageSize); const pageNumber = Number(req.query.pageNumber)-1; connection.query(`SELECT * FROM blog`, (error, results, fields) => { if (!error) { obj.total = results.length; // 分頁查詢 begin connection.query(`SELECT * FROM blog limit ${pageNumber*pageSize}, ${pageSize}`, (error, results, fields) => { if (!error) { obj.ret = true; obj.rows = results; res.header("Access-Control-Allow-Origin", "*"); res.type('application/json'); res.jsonp(obj); }else{ next(error); } }) // 分頁查詢 end }else{ next(error); } }) }) app.get("/404", (req, res) => { res.render("404.html"); }) // 配置一個全域性錯誤處理中介軟體 app.use(function (err, req, res, next) { res.status(500).json({ err_code: 500, message: err.message }) }) app.listen(5555, () => { console.log("服務啟動成功......"); })