需要帮助Store并使用react js,node js,MySQL和webpack检索数据

时间:2016-11-26 12:00:13

标签: express reactjs react-router webpack-dev-server node-mysql

以下是用于创建UI的反应代码。我添加了将数据存储到MySQL的代码。这部分不起作用。

ContactUsClass.js

import React from 'react';
require('./styles.css');
//my SQL code (not working) - start
require('node-mysql');
var mysql = require('mysql');
//my SQL part - end
class ContactUsClass extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            text: {
                n: '',
                m: '',
                p: '',
                msg:''
            }
        };
        this.handleSubmit = this
            .handleSubmit
            .bind(this);
    }
    handleChange(pty, event)
    {
        const text = this.state.text;
        text[pty] = event.target.value;
        this.setState({text: text});
    }

    handleSubmit(event)
    {
        alert('Text field value is: ' + this.state.text.e + '\nExtra:' + this.state.text.c + '\nTA:' + this.state.text.msg);
        //mysql code (not working) - start
        var connection = mysql.createConnection({host: '127.0.0.2', user: 'root', password: 'admin', database: 'dbcontactus'});
        connection.connect(function (err) {
            if (!err) {
               alert("Database is connected ... ");
            } else {
                alert("Error connecting database ... ", err);
            }
        });

        var user = {
            'clientname': 'CH Yamini Sankar',
            'email': 'mail@mail.com',
            'phonenumber': '9999454551',
            'message': 'hello world'
        };
        connection.query('Insert into tbcontactus SET ?', user, function (err, res) {
            connection.end();
            if (!err) 
                alert('The solution is: ', res);
            else 
                alert('Error while performing Query.', err);
            }
        );
        //mysql code (not working) - end
    }
    render()
    {
        return (
            <div className="mainbox">
                <div className="heading">
                    Contact Us</div>
                <div><br/></div>
                <div>
                    <input
                        className="tbox"
                        type="text"
                        placeholder="Name"
                        value={this.state.text.e}
                        onChange={this
                        .handleChange
                        .bind(this, 'e')}/>
                    <input
                        className="tbox"
                        type="text"
                        placeholder="E-mail ID"
                        value={this.state.text.c}
                        onChange={this
                        .handleChange
                        .bind(this, 'c')}/>
                </div>
                <div>
                    <input
                        className="tpbox"
                        type="text"
                        placeholder="Mobile/Phone no: +1"
                        value={this.state.text.p}
                        onChange={this
                        .handleChange
                        .bind(this, 'p')}/>
                </div>

                <div>
                    <textarea
                        className="mbox"
                        type="text"
                        placeholder="Message"
                        value={this.state.text.msg}
                        onChange={this
                        .handleChange
                        .bind(this, 'msg')}/>
                </div>

                <div>
                    <button className="btn" onClick={this.handleSubmit}>Submit</button>
                </div>
            </div>
        );
    }
}

export default ContactUsClass;

ContactUsMain.js

import React from 'react';
import ReactDOM from 'react-dom';
import ContactUsClass from './ContactUsClass.js';

ReactDOM.render(
    <ContactUsClass/>, document.getElementById('container'));

ContactUs.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Contact Us</title>
</head>

<body>
    <div id="container"></div>
    <script src="BundleContactUs.js"></script>
</body>

</html>

webpack.config.js

var config = {
    entry: './ContactUsMain.js',

    output: {
        path: './',
        filename: 'BundleContactUs.js'
    },

    devServer: {
        inline: true,
        port: 8080
    },

    module: {
        loaders: [{
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel',

                query: {
                    presets: ['latest', 'react']
                }
            }, {
                test: /\.css?$/,
                exclude: /node_modules/,
                loader: 'style-loader!css-loader'
            }

        ]
    },
    node: {
        net: 'empty',
        tls: 'empty',
        dns: 'empty',
        fs: 'empty'
    }
}

module.exports = config;

的package.json

{
    "name": "hrportal",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "start": "webpack-dev-server --hot",
        "test": "node ContactUsConn.js"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
        "babel-core": "^6.18.2",
        "babel-loader": "^6.2.8",
        "babel-preset-latest": "^6.16.0",
        "babel-preset-react": "^6.16.0",
        "css-loader": "^0.26.0",
        "mysql": "github:mysqljs/mysql",
        "node-mysql": "^0.4.2",
        "popup": "0.0.3",
        "react": "^15.4.0",
        "react-dom": "^15.4.0",
        "style-loader": "^0.13.1",
        "webpack": "^1.13.3",
        "webpack-dev-server": "^1.16.2"
    }
}

以下是styles.css

.mainbox {
    width: 40%;
    margin: 0 auto;
    height: 500px;
    background-color: white;
}

.lbox {
    width: 50px;
    float: left;
    height: 100px;
    background-color: maroon;
}

.rbox {
    width: 50px;
    float: right;
    height: 100px;
    background-color: maroon;
}

.heading {
    width: 25%;
    padding: 15px;
    border-bottom-style: solid;
    border-radius: 5px;
    border-bottom-color: gray;
    margin: 0 auto;
    font-size: 24px;
    font-weight: 500;
    font-family: 'Roboto', sans-serif;
    text-align: center;
    color: gray;
}

.tbox {
    width: 48%;
    height: 35px;
    padding: 4px;
    margin: 1%;
    margin-bottom: 10px;
    box-sizing: border-box;
}

.tpbox {
    width: 98%;
    height: 35px;
    padding: 4px;
    margin: 1%;
    margin-bottom: 10px;
    box-sizing: border-box;
}

.mbox {
    width: 98%;
    padding: 4px;
    height: 125px;
    margin: 1%;
    margin-bottom: 10px;
    box-sizing: border-box;
}

.btn {
    width: 100px;
    height: 35px;
    padding: 4px;
    margin: 0 auto;
}

body {
    background-color: #F0EDED;
}

使用上述五个文件我想将网页中的数据存储到数据库中,反之亦然。

1 个答案:

答案 0 :(得分:3)

您正尝试通过客户端代码直接访问MySQL数据库,但这应该在您的服务器上完成。有关详细信息,请参阅this question/answer

您在客户端应该做的是通过ajax调用提交数据。然后,在您的服务器上,您应该解析请求并将数据插入数据库。

实施例

ContactUs组件中,您可以将数据提交到服务器。以下示例使用Fetch API

ContactUs.jsx

class ContactUs extends React.Component {

  handleSubmit(event) {
    var user = {
        'clientname': 'CH Yamini Sankar',
        'email': 'mail@mail.com',
        'phonenumber': '9490430491',
        'message': 'hello world'
    };

    fetch('/api/contact-us', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(user)
    })
  }

  render() {
    // ...
  }

}

服务器的语言取决于你,但由于我们正在讨论JavaScript,我将展示一个使用express的节点服务器。

server.js

app.use(express.bodyParser());

app.post('/api/contact-us', (req, res) => {
  // connect to your MySQL database and insert the data
})