I can't fetch react form - json

Hi I try to make simple contact from in react, but I stuck on fetch() method.
This is my code. I have no idea what is wrong.
FrontEnd
export default class ContactForm extends React.Component<IContactFormProps, any> {
constructor(props) {
super(props);
// local state
this.state = {
tl: new TimelineMax({paused: true, delay: 1}),
name: "",
email: "",
subject: "",
message: "",
sent: false,
}
this.handleOnSubmit = this.handleOnSubmit.bind(this);
this.handleClearForm = this.handleClearForm.bind(this);
this.handleChange = this.handleChange.bind(this);
this.startAnimation = this.startAnimation.bind(this);
}
handleOnSubmit(e) {
console.log("ContactForm->handleOnSubmit(e).");
e.preventDefault();
let formData = new FormData();
formData.append(name, this.state.name);
console.log("formData: " + formData);
fetch('/contact', {
method: 'POST',
body: formData
})
.then((response) => {
console.log("response: " + response);
console.log("response.ok: " + response.ok);
return response.json();
})
.then((responseJson) => {
console.log("responseJson: " + responseJson);
})
.catch((error) => {
console.log("error from fetch: " + error);
});
}
handleClearForm(e) {
console.log("ContactForm->handleClearForm(e).");
// e.preventDefault();
}
handleChange(event) {
const target = event.target;
const name = event.target.name;
const value = event.target.value;
this.setState({
[name]: value
});
// console.log("event.target.value: " + event.target.value);
// this.setState({value: event.target.value});
}
startAnimation() {
console.log("ContactForm->startAnimation().");
}
componentDidMount() {
this.startAnimation();
}
componentWillUnmount() {
}
render() {
return (
<form className="contact-form-cnt"
onSubmit={ this.handleOnSubmit }>
<div className="top-row">
<input type="text" name="name" placeholder="Name"
className="name" ref="name"
value={this.state.name} onChange={this.handleChange}/>
<input type="text" name="email" placeholder="Em#il"
className="email" ref="email"
value={this.state.email} onChange={this.handleChange}/>
</div>
<input type="text" name="subject" placeholder="Subject"
className="subject" ref="subject"
value={this.state.subject} onChange={this.handleChange}/>
<textarea name="message" placeholder="Write Your message here."
className="message" ref="message"
value={this.state.message} onChange={this.handleChange}></textarea>
<button type="submit" name="submit"
className="submit" ref="Send"
onClick={ this.handleClearForm }>Send</button>
</form>
);
};
};
BackEnd
'use strict';
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const winston = require('winston');
const distPath = path.join(__dirname, '../dist');
const indexFileName = 'index.html';
const app = express();
const PORT = process.env.PORT || 8080;
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(express.static(distPath));
app.get('*', (req, res) => res.sendFile(path.join(distPath, indexFileName)));
app.post("/contact", (req, res) => {
try {
console.log("mail sending succes!");
}
catch ( error ) {
console.log("mail sending failure!");
}
});
app.listen(PORT, (err) => {
if (err) {
winston.error(err);
return;
}
winston.info(`Listening on port ${PORT}`);
});
URL:
http://localhost:8080/contact
and error
POST http://localhost:8080/contact 404 (Not Found)
I think it's something with url, but I'am out of ideas. Any sugestions?

try something like this:
app.post("/contact", (req, res) => {
res.json({"foo": "bar"});
});
this way you are setting an json object as result. Let me know if works.

Related

How can I edit using MySQL , NodeJs, React Js,

I've been trying to figure this out for hours, but i think im doing it wrong. So what im basically doing is.
-> Fetch the specific user, and throw it into the placeholder -> which is working
but when I try to edit the information and then when i try to save it this error shows and then in my phpadmin, it saves a null. it seems that I can't connect the front and the backend.
sql: 'UPDATE users SET name = NULL, email = NULL, mobile = NULL WHERE id = ${id} '
Edit.jsx
import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
const EditUser = () => {
const navigate = useNavigate()
const [data, setData] = useState([])
const [inputs, setInputs] = useState([])
const { id } = useParams()
useEffect(() => {
const getUser = async () => {
const res = await axios.get(`http://localhost:5000/${id}`)
setData(res.data[0])
}
getUser()
}, [])
const handleSubmit = async () => {
try {
await axios.put(`http://localhost:5000/${id}`, inputs)
} catch (error) {
console.log(error)
}
}
const handleChange = (e) => {
setInputs({ ...inputs, [e.target.name]: e.target.value })
}
return (
<div>
<form
action=""
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
}}
onSubmit={handleSubmit}
>
<label htmlFor="">Name</label>
<input type="text" placeholder={data.name} onChange={handleChange} />
<label htmlFor="">Email</label>
<input type="text" placeholder={data.email} onChange={handleChange} />
<label htmlFor="">Mobile</label>
<input type="text" placeholder={data.mobile} onChange={handleChange} />
<button type="submit">save</button>
</form>
</div>
)
}
export default EditUser
backend.js
app.put('/:id', (req, res) => {
const id = req.params.id
const name = req.body.name
const email = req.body.email
const mobile = req.body.mobile
pool.query(
`UPDATE users SET name = ?, email = ?, mobile = ? WHERE id = ${id} `,
[name, email, mobile],
(err, result) => {
if (err) {
console.log(err)
} else {
res.send(result)
}
}
)
})
app.get('/:id', (req, res) => {
const { name, email, mobile } = req.body
const { id } = req.params
pool.query(`SELECT * FROM users WHERE id = ${id} `, (err, result) => {
if (err) {
console.log(err)
} else {
res.send(result)
}
})
})
May be you should try :
The following states :
const EditUser = () => {
const navigate = useNavigate()
const [data, setData] = useState([])
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [mobile, setMobile] = useState("")
const { id } = useParams()
For your request :
const handleSubmit = async () => {
let datas ={
name: name,
email: email,
mobile: mobile
}
try {
await axios.put('http://localhost:5000/updateUser/'+id, datas)
} catch (error) {
console.log(error)
}
}
Then you just update your states that way :
<form
action=""
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
}}
onSubmit={handleSubmit}
>
<label htmlFor="">Name</label>
<input type="text" placeholder={data.name} onChange={()=>
{setName(e.currentTarget.value)} />
<label htmlFor="">Email</label>
<input type="text" placeholder={data.email} onChange={()=>
{setEmail(e.currentTarget.value)} />
<label htmlFor="">Mobile</label>
<input type="text" placeholder={data.mobile} onChange={()=>
{setMobile(e.currentTarget.value)} />
<button type="submit">save</button>
</form>
For you back end maybe you should add some informations in the adress (to avoid confusion with you app.get):
app.put('updateUser/:id', (req, res) => {
const id = req.params.id
const name = req.body.name
const email = req.body.email
const mobile = req.body.mobile
pool.query(
`UPDATE users SET name = ?, email = ?, mobile = ? WHERE id = ${id} `,
[name, email, mobile],
(err, result) => {
if (err) {
console.log(err)
} else {
res.send(result)
}
}
)
})
I hope it will help you !
I think I did it actually, but I dont know if this is the right method. so what i did is
instead of directing submit it as an await
const handleSubmit = async () => {
try {
await axios.put(`http://localhost:5000/${id}`, inputs)
} catch (error) {
console.log(error)
}
}
i did this.
const handleSubmit = async (e) => {
e.preventDefault()
try {
const res = await axios.put(`http://localhost:5000/${id}`, inputs)
setInputs(res.data)
} catch (error) {
console.log(error)
}}
Hey guys, if its wrong, please show me the other way.

ReactJS NodeJs after delete method everything stop working

Hello i was worked on crud app everything is worked fine but when i create delete route i cannot post data to server i get empty string and error cannot get if i follow get link i try to comment all delete methods but still no one is working even toast are stopped working works only navigate buttons ..
Server
index.js
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mysql = require("mysql");
const cors = require("cors");
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "crud_contact",
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/api/get", function(req,res){
console.log('Hello');
db.query('SELECT * FROM contact_db', function (error, result) {
res.send(result);
});
});
app.post("/api/post", (req, res) => {
const {name, email, contact} = req.body;
const sqlInsert =
`INSERT INTO contact_db (name,email, contact)
VALUES (?, ?, ?)`;
db.query(sqlInsert, [name, email, contact], (error,result) => {
res.send(result);
if(error) {
console.log(error);
}
});
})
// app.delete("/api/remove/:id", (req, res) => {
// const {id} = req.params;
// const sqlRemove =
// `DElETE FROM contact_db WHERE id = ?`;
// db.query(sqlRemove, id , (error,result) => {
// if(error) {
// console.log(error);
// }
// });
// })
//
app.get("/", (req, res) => {
// app.listen(5000, () => {
// con.connect(function(err) {
// if (err) throw err;
// console.log("Connected!");
// var sql = `INSERT INTO contact_db(name,email, contact)
// VALUES('popas','berazumis#gmail.com',8585858)`;
// con.query(sql, function (err, result) {
// if (err) throw err;
// console.log("record inserted");
// });
// });
// });
});
app.listen(5000, () => {
console.log("Listening port 5000");
});
Client
Add edit user
AddEdit.js
import React, { useState, useEffect } from "react";
import { useNavigate, useParams, Link } from "react-router-dom";
import "./AddEdit.css";
import axios from "axios";
import { toast } from "react-toastify";
const initiaState = {
name: "",
email: "",
contact: "",
};
const AddEdit = () => {
const [state, setState] = useState(initiaState);
const { name, email, contact } = state;
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefault();
if (!name || !email || !contact) {
toast.error("Please fill all labels below");
} else {
axios
.post("http://localhost:5000/api/post", {
name,
email,
contact
})
.then(() => {
setState({ name: "", email: "", contact: "" });
})
.catch((err) => toast.error(err.response.data));
setTimeout(() => navigate.push("/"), 500);
}
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setState({ ...state, [name]: value });
};
return (
<div style={{ marginTop: "100px" }}>
<form
style={{
margin: "auto",
padding: "15px",
maxWidth: "400px",
alignContent: "cener",
}}
onSubmit={handleSubmit}
>
<label htmlFor="name">Name</label>
<input
type="text"
id="name"
name="name"
placeholder="Type Name..."
value={name}
onChange={handleInputChange}
/>
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
name="email"
placeholder="Type Email..."
value={email}
onChange={handleInputChange}
/>
<label htmlFor="contact">Contact</label>
<input
type="number"
id="contact"
name="contact"
placeholder="Type contact number"
value={contact}
onChange={handleInputChange}
/>
<Link to="/">
<input type="submit" value="save" />
<input type="button" value="Go Back" />
</Link>
</form>
</div>
);
};
export default AddEdit;
Home.js
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import "./Home.css";
import { toast } from "react-toastify";
import axios from "axios";
const Home = () => {
const [data, setData] = useState([]);
const loadData = async () => {
const response = await axios.get("http://localhost:5000/api/get");
setData(response.data);
};
useEffect(() => {
loadData();
}, []);
/* const deleteContact = (id) => {
if(window.confirm("Are you sure that you wanna delete contact")) {
axios.delete(`http://localhost:5000/api/remove/${id}`);
toast.success("Contact Deleted Successfully");
setTimeout(() => loadData(), 500);
}
}
*/
return (
<div style={{ marginTop: "150px" }}>
<Link to="addContact">
<button className="btn btn-contact">Add contact</button>
</Link>
<table className="styled-table">
<thead>
<tr>
<th style={{ textAlign: "center" }}>No.</th>
<th style={{ textAlign: "center" }}>Name</th>
<th style={{ textAlign: "center" }}>Email</th>
<th style={{ textAlign: "center" }}>Contact</th>
<th style={{ textAlign: "center" }}>Action</th>
</tr>
</thead>
<tbody>
{data.map((item, index) => {
return (
<tr key={item.id}>
<th scope="row">{index + 1}</th>
<td>{item.name}</td>
<td>{item.email}</td>
<td>{item.contact}</td>
<td>
<Link to={`/update/${item.id}`}>
<button className="btn btn-edit" >Edit</button>
</Link>
<button className="btn btn-delete" /*onClick={() => deleteContact}*/ >Delete</button>
<Link to={`/view/${item.id}`}>
<button className="btn btn-view">View</button>
</Link>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
export default Home;
When you create a app.delete route, you no longer use POST method on your client side, you need to use the DELETE method.
Client Side Example
const res = await axios.delete('https://example.com/delete', { data: { answer: 42 } });
Server Side Example
app.delete('/delete', async(req, res,next) => {
console.log('req.body', req.body)
//prints { data: { answer: 42 } }
})

Axios post is giving me an error: Internal server Error

I am doing a post request with Axios and gives me this error:
xhr.js:178 POST http://localhost:3000/dependentes 500 (Internal Server
Error)
I have seen people asking about this but none of their solutions work for me!
I don't know if is something wrong in this component or I have something wrong with the server side.
import React, { Component } from "react";
import axios from "axios";
class LogIn extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeEmail = this.handleChangeEmail.bind(this);
this.handleChangePass = this.handleChangePass.bind(this);
}
handleChangeEmail = e => {
this.setState({ email: e.target.value });
//console.log(e.target.value);
};
handleChangePass = e => {
this.setState({ password: e.target.value });
//console.log(e.target.value);
};
handleSubmit = e => {
/*this.props.history.push('/');
console.log(this.props);*/
event.preventDefault();
let data = JSON.stringify({
email: this.state.email,
password: this.state.password
});
let url = "http://localhost:3000/dependentes";
const response = axios.post(url, data, {
headers: { "Content-Type": "application/json" }
});
};
render() {
return (
<div className="container">
<form onSubmit={this.handleSubmit} className="white">
<h5 className="grey-text text-darken-3">Log In</h5>
<div className="input-field">
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
onChange={this.handleChangeEmail}
value={this.state.email}
/>
</div>
<div className="input-field">
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
onChange={this.handleChangePass}
/>
</div>
<div className="input-field">
<button className="btn orange lighten-1 z-depth-0">Log In</button>
</div>
</form>
</div>
);
}
}
export default LogIn;
According to your node.js code you are NOT using body-parser that's why getting email from req.body will throw you an error because req.body is undefined.
Also, If you don't return the request like res.send or res.json it will always time out from front end as the request is not closed.
So, to edit your code
//installed express, mysql, cors
const config = require('./database/config');
const express = require('express');
const cors = require('cors');
const port = 4000;
const app = express();
const mysql = require('mysql');
const bodyParser = require('body-parser'); // <=== this line
app.use(cors());
app.use(bodyParser.json()); //<=== This line
const SELECT_ALL_ADDICTS_QUERY = 'SELECT * FROM viciados';
const connection = mysql.createConnection(config.mysql);
connection.connect(err => {
if (err) {
return err;
}
});
app.get('/', (req, res) => {
res.send('Homepage. Go to /dependentes para ver os dependentes no sistema');
res.end();
});
app.get('/dependentes', (req, res) => {
connection.query(SELECT_ALL_ADDICTS_QUERY, (err, results) => {
if (err) {
res.send(err);
} else {
res.json({
data: results
});
}
});
});
app.post('/dependentes', (req, res) => {
console.log(req.body.email);
res.json({ email: req.body.email }); ///<== and this line
});
app.listen(port, err => {
return err
? console.log(`error founded: ${err}`)
: console.log(`server runnning on port: ${port}`);
});

Handling GET request with axios and express

I am really new to react. I created a simple form with bootstrap.
I created a MySQL database. I set up an express server on port 3001 and was able to post my form data to the database successfully.
Now I am trying to send an id through the form and get the details. Can someone please guide me through this. I looked over the internet but could not find a clear example yet.
Thanks in advance
My app.js:
import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
import "./App.css";
import axios from "axios";
import { Form } from "react-bootstrap";
class App extends Component {
constructor(props) {
super(props);
this.state = {
id: "",
fName: "",
lName: "",
password: "",
email: "",
persons: [],
};
}
handleOnSubmit(event) {
event.preventDefault();
alert("Data Submitted Successfully");
//--------------------------------------------------------------------------------
//POST Request
// const user = {
// fName : this.state.fName,
// lName : this.state.lName,
// // email : this.state.email,
// // password : this.state.password,
// };
// axios.post(`http://localhost:3001`, { user })
// .then(res => {
// console.log(res);
// console.log(res.data);
// })
}
handleOnChange(event) {
let name = event.target.name;
let value = event.target.value;
this.setState({
[name]: value
});
}
//GET Request
handleOnSearch() {
axios.get(`http://localhost:3001`,{
params: {
id: this.state.id
}
})
.then(res => {
console.log(this.state.persons);
this.setState({ persons: res.data });
});
}
render() {
return (
<div>
<Form onSubmit={this.handleOnSubmit.bind(this)}>
<Form.Group controlId="firstName">
<Form.Label>First Name</Form.Label>
<Form.Control
type="text"
placeholder="Enter first name"
name="fName"
onChange={this.handleOnChange.bind(this)}
/>
</Form.Group>
<Form.Group controlId="lastName">
<Form.Label>Last Name</Form.Label>
<Form.Control
type="text"
placeholder="Enter last name"
name="lName"
onChange={this.handleOnChange.bind(this)}
/>
</Form.Group>
<div>
<button
variant="primary"
type="submit"
className="btn btn-primary mx-1"
>
Submit
</button>
<button variant="primary" type="reset" className="btn btn-warning">
Clear
</button>
</div>
<hr />
<br />
<div>
<Form.Group controlId="id">
<Form.Label>Id</Form.Label>
<Form.Control
type="text"
placeholder="Enter id"
name="id"
onChange={this.handleOnChange.bind(this)}
/>
</Form.Group>
<button variant="primary" className="btn btn-warning mx-1" onClick={this.handleOnSearch.bind(this)}>
Search
</button>
</div>
</Form>
</div>
);
}
}
export default App;
my server.js:
// Creating the express app
var express = require('express');
var app = express();
// Getting mysql database access
var mysql = require('mysql');
// Enabling support to the Cross-Origin Resource Sharing protocol
var cors = require('cors');
app.use(cors());
// Extracting the body of the req to expose it on command
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Writing connection details
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'reactmysql'
})
// Connecting to the database
con.connect((err) => {
if (err) {
console.log("There was an error connecting to the database: " + err);
}
console.log("Connected to the database");
})
// Starting listening on port 3001
app.listen(3001, () => {
console.log("I am listening on port 3001");
})
// Getting the data from the body whenever user inputs them and assigning them to backend variables
app.post('/', (req, res) => {
// var fName = req.body.user.fName
// var lName = req.body.user.lName
console.log(req);
console.log(res);
// var sql = "INSERT INTO ('firstname', 'lastname') VALUES ('" + fName + "', '" + lName + "')"
var sql = "SELECT * FROM `mytable`";
con.query(sql, (err, result) => {
if (err) {
console.log("There was an error in your query: " + err);
}
console.log("Query Executed Successfully");
console.log(result)
})
})
Add the express host in package.json of react app
"proxy": "http://localhost:3001/"
app.js
//GET Request
handleOnSearch() {
axios.get(`/${this.state.id}`
})
.then(res => {
console.log(this.state.persons);
this.setState({ persons: res.data });
});
}
server.js
app.get('/:id', (req, res) => {
const id = req.params.id;
//Rest of the code
})
edit
You can try this with your old code
In app.js add preventDefault()
handleOnSearch(event) {
event.preventDefault();
axios
.get(`http://localhost:3001`, {
params: {
id: this.state.id,
},
})
.then((res) => {
console.log(this.state.persons);
this.setState({ persons: res.data });
});
}
server.js
app.get('/', (req, res) => {
const id = req.query.id;
//Rest of the code
})
Use this with all handling.
axios.get('/:id', {
params: {
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});

ReactJS connection with database

I want to get the data from front end react js form and insert in to mysql database using backend express. Can you tell me the flow from front end to backend with simple one field form using react js and then insert into database.
Lets take an example of a simple library application having table(books) with fields book_name and author .
Lets see the Backend Code First(in 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`);
});
Now Let's see the Front End code on 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" 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>
)
}
}
Here's a simple example that establishes a connection to 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
**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;