react connect to database code example
Example 1: 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',
user: 'userEHX',
password : 'hMmx56FN4GHpMXOl',
port : 3306,
database:'sampledb'
},'pool'));
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){
res.status(400).json('Sorry!!Unable To Add'));
console.log("Error inserting : %s ",err );
}
else
res.status(200).json('Book Added Successfully!!')
});
});
app.listen(3000, ()=> {
console.log(`app is running on port 3000`);
});
Example 2: connect react with database server
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)
})
}
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>
)
}
}