connect react with database server

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`);
});

5
2

                                    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" value{this.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>

    )

}




 }

5 (2 Votes)
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Relative searches
connect my react app to mysql database Database connection in React.js connect database with database reactjs how to connect react js to sql server react js connect with database ? react connect sql server how to connect react to backend database how to connect sql server database with react connect to database in react reactjs connect to ms sql server reactjs connect to sql server How to connect to database on another sever react what is the easiest database to connect to reactjs connect a react app to a database can react connect to database react js connect to database mysql react app connect to database best database to connect on react react js connect to sql database how to connect database with react app how to connect to db in react How to connect React js with SQL server database connect sql server react connect react app to local database connect react to sql database connect with db with react react js connect to database which thing is used for the connect database in react app how to connect react application to sql database how to connect to sql server in react js itself how to integrate database with react js app connect to db using react connect react app to mysql database react connect with database can we connect database with react js without node how to connect react app with database connect react app to sql database how to connect a database in react how to connect to database using react how to connect react app to mssql database how to connect react app to sql database connecting database to react connect to db react reactjs connect to database creating database connection in react best way to connect db to react app react connect to db how to connect react js with sql database how to connect database with react js how to access to database from react database connection in react js react connect to database react js database connection react database connection react database connection mysql react connect to sql server database connect react with database server
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source