1const express = require('express');
2const bodyParser = require('body-parser');
3var connection = require('express-myconnection');
4var mysql = require('mysql');
5
6const app = express();
7app.use(bodyParser.json());
8
9app.use(
10
11 connection(mysql,{
12
13 host: 'localhost', //'localhost',
14 user: 'userEHX',
15 password : 'hMmx56FN4GHpMXOl',
16 port : 3306, //port mysql
17 database:'sampledb'
18
19 },'pool')); //or single
20
21 app.post('/add_book',(req,res)=>{
22
23 let {book_name,author,} = req.body;
24
25
26 if(!book_name) return res.status(400).json('Book Name cant be blank');
27 if(!author) return res.status(400).json('Author cant be blank');
28
29 var data={book_name:book_name,
30 author:author};
31
32
33 var query = connection.query("INSERT INTO books set ? ",data,
34 function(err, rows)
35 {
36
37 if (err){
38 //If error
39 res.status(400).json('Sorry!!Unable To Add'));
40 console.log("Error inserting : %s ",err );
41 }
42 else
43 //If success
44 res.status(200).json('Book Added Successfully!!')
45
46 });
47
48
49 });
50
51
52 app.listen(3000, ()=> {
53 console.log(`app is running on port 3000`);
54});
55
1import React from 'react';
2export default class AddBook extends React.Component {
3
4constructor(){
5 super();
6 this.state = {
7 bookname:'',
8 author:'',
9
10 };
11
12 }
13
14
15updateInfo = (event) =>{
16 let fieldName = event.target.name;
17 let fieldValue = event.target.value;
18 if(fieldName === 'bookname') {
19 this.setState({bookname: fieldValue});
20 }
21 else if(fieldName === 'author'){
22 this.setState({author:fieldValue});
23 }
24};
25
26
27addBook=(e)=>{
28
29 let {bookname,author}=this.state;
30 fetch('localhost:3000/add_book', {
31 method: 'post',
32 headers: {'Content-Type': 'application/json'},
33 body: JSON.stringify({
34 bookname:bookname,
35 author:author,
36
37 })
38 }).then(response=>response.json()).then(data=>{
39 window.alert(data)
40 //Do anything else like Toast etc.
41})
42
43}
44
45render(){
46
47return(
48
49
50
51<div className="add_book">
52
53 <div>
54 <label>Book Name</label>
55 <input onChange={this.updateInfo} name="bookname" value{this.state.bookname}/>
56 </div>
57 <div>
58 <label >Author</label>
59 <input onChange={this.updateInfo} name="author" value={this.state.author}/>
60</div>
61
62<button onClick={this.addBook}>Add</button>
63
64</div>
65
66 )
67
68}
69
70
71
72
73 }
74