ReactJS 与数据库的连接

Posted

技术标签:

【中文标题】ReactJS 与数据库的连接【英文标题】:ReactJS connection with database 【发布时间】:2017-09-13 20:43:59 【问题描述】:

我想从前端 react js 表单中获取数据并使用后端 express 插入到 mysql 数据库中。你能告诉我从前端到后端的流程吗?使用 react js 的简单字段表单,然后插入数据库。

【问题讨论】:

我已经在 reactjs 中制作了注册表单。 人们会犹豫是否要提供帮助,直到您表明您已经做出了努力。发布一些您已阅读的文档的链接。展示您编写此代码的尝试,然后发布您的代码并寻求帮助 有道理..绝对正确 我真的不明白你不知道什么。您提出问题的方式听起来好像您对 Web 开发一无所知,这可能会导致与您期望的答案不同。请说明您不知道的内容,以便我们根据情况回答 【参考方案1】:

让我们举一个简单的库应用程序示例,该应用程序具有表 (books),其中字段为 book_nameauthor

让我们先看看后端代码(在 Node Js 中)

const express = require('express');
const bodyParser = require('body-parser');
var connection  = require('express-myconnection'); 
var mysql = require('mysql');

const app = express(); 
app.use(bodyParser.json());

app.use(

        connection(mysql,

            host: 'localhost', //'localhost',
            user: 'userEHX',
            password : 'hMmx56FN4GHpMXOl',
            port : 3306, //port mysql
            database:'sampledb'

        ,'pool')); //or single

       app.post('/add_book',(req,res)=>

        let book_name,author, = req.body;


        if(!book_name) return res.status(400).json('Book Name cant be blank');
        if(!author) return res.status(400).json('Author cant be blank');

        var data=book_name:book_name,
                  author:author;


         var query = connection.query("INSERT INTO books set ? ",data, 
        function(err, rows)
        

          if (err)
            //If error
              res.status(400).json('Sorry!!Unable To Add'));
              console.log("Error inserting : %s ",err );
             
         else
          //If success
          res.status(200).json('Book Added Successfully!!')

        );


        );


         app.listen(3000, ()=> 
      console.log(`app is running on port 3000`);
);

现在让我们看看 React Js 上的前端代码:

import React from 'react';
export default class AddBook extends React.Component 

constructor()
        super();
        this.state = 
            bookname:'',
            author:'',

        ;

    


updateInfo = (event) =>
        let fieldName = event.target.name;
        let fieldValue = event.target.value;
        if(fieldName === 'bookname') 
            this.setState(bookname: fieldValue);
        
        else if(fieldName === 'author')
            this.setState(author:fieldValue);
        
;


addBook=(e)=>

 let bookname,author=this.state;
 fetch('localhost:3000/add_book', 
      method: 'post',
      headers: 'Content-Type': 'application/json',
      body: JSON.stringify(
        bookname:bookname,
        author:author,

      )
    ).then(response=>response.json()).then(data=>
         window.alert(data)
         //Do anything else like Toast etc.
)



render()

return(



<div className="add_book">

 <div>
    <label>Book Name</label>
    <input onChange=this.updateInfo name="bookname" valuethis.state.bookname/>
 </div>
 <div>
  <label >Author</label>
  <input onChange=this.updateInfo name="author" value=this.state.author/>
</div>

<button onClick=this.addBook>Add</button>                                 

</div>

    )






 

【讨论】:

【参考方案2】:

**On REACT**

import React,  Component  from 'react';
import axios from "axios";
import 
  BrowserRouter as Router,
  Route,
  Link,
  Redirect,
  withRouter
 from "react-router-dom";

import createHistory from "history/createBrowserHistory"

//import isLoggedIn from '../../helpers/is_logged_in';
class Login extends Component 


   constructor(props) 
    const history = createHistory();
      super(props);

     // this.islogin = this.islogin.bind(this);
      this.signIn = this.signIn.bind(this);
      this.handleEmailChange = this.handleEmailChange.bind(this);
      this.handlePasswordChange = this.handlePasswordChange.bind(this);
      this.state = 
        email:'',
        password:'',
        redirectToReferrer: false

      ;
    
    signIn()

      const history = createHistory()
      const location = history.location;
              console.log(location);


    //  alert(this.state.email);
      axios.post('http://192.168.1.35:3012/users', 
        email: this.state.email,
        password: this.state.password
      )
      .then(function (response) 
       // console.log(response.data[0].id);
       // console.log(response.data.email);
        var das =  localStorage.setItem('sessionid', response.data[0].id);
        var das =  localStorage.setItem('myData', response.data[0].name);
       var da =  localStorage.getItem('myData');
      var myid =  sessionStorage.setItem('myid', response.data[0].id);
      //alert(da);
       //history.go('/dash');
       
      )

      .catch(function (error) 
        console.log(error);
      );

       this.setState( redirectToReferrer: true );
    


    handleEmailChange(e)
      this.setState(email:e.target.value)
    
    handlePasswordChange(e)
      this.setState(password:e.target.value)


  render() 
    console.log('11111');
          const myid =  sessionStorage.getItem('myid');
      const  from  = this.props.location.state ||  from:  pathname: "/dash"  ;
    const  redirectToReferrer  = this.state;

    if (redirectToReferrer || myid !=null) 
          console.log('22222');

      return <Redirect to=from />;
    

else

    return (
            <form className="form-signin" history=this.props.history>
                <h2 className="form-signin-heading"> Please sign in </h2>
                <label className="sr-only"> Email address
                </label>

<input type="email" onChange=this.handleEmailChange id="inputEmail" className="form-control" placeholder="Email address" required />              
  <label htmlFor="inputPassword" className="sr-only"> Password</label>

<input type="password" onChange=this.handlePasswordChange id="inputPassword" className="form-control" placeholder="Password" required />  

<button className="btn btn-lg btn-primary btn-block" onClick=this.signIn type="button">Sign in</button>            
            </form> 
    );
  


export default withRouter(Login); 



**On Express**


var express = require('express');
var bodyParser   = require('body-parser');
var app = express();
 var fs = require('fs');
var formidable = require('formidable');
var busboy = require('connect-busboy');
var cors = require('cors')
var router = express.Router();

app.use(function(req, res, next) 
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
);

var mysql = require('mysql')
var connection = mysql.createConnection(
  host     : 'localhost',
  user     : 'root',
  password : 'test',
  database : 'example'
);

connection.connect(function(err) 
  if (err) throw err
 // console.log('You are now connected...')
)

/* POST users listing. */
router.post('/', function(req, res, next) 

  console.log(req.body.email);
      user_sql = "INSERT INTO table_name VALUES (req.body.name, req.body.password);

     console.log(user_sql)
  connection.query(user_sql, function (err, rows, fields) 
  if (err) throw err

console.log(rows)
res.end(JSON.stringify(rows));

   // res.json(rows);
);

   
       
 
);


module.exports = router;

【讨论】:

请在您的代码中添加说明。此外,您的代码 sn-p 不起作用,因此要么使其工作,要么删除将代码用作代码 sn-p 的功能。【参考方案3】:

这是一个建立与 mysql 的连接的简单示例。

var mysql = require('mysql')
var connection = mysql.createConnection(
host     : 'localhost',
user     : 'dbuser',
password : 's3kreee7',
database : 'my_db'
);

connection.connect()

connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) 
if (err) throw err

console.log('The solution is: ', rows[0].solution)
)

connection.end()

Helpful guide to integrate popular Node.js modules for DBs

【讨论】:

以上是关于ReactJS 与数据库的连接的主要内容,如果未能解决你的问题,请参考以下文章

如何将 SQL Server 数据库(表)与 React JS 项目连接起来

Reactjs 和 Mongodb 的连接

如何与firebase建立内部连接并与其连接reactjs前端[关闭]

如何使用react js连接mysql数据库[重复]

ReactJS - 如何在将数据发布到数据库后重新渲染功能组件

如何从reactjs发出Http请求?