Axios post is giving me an error: Internal server Error - mysql

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

Related

404 NOT FOUND react and node js

I'm trying to do a post with a form on react, but when i submit for the name, the browser console always show "404 not found localhost:3000/store-data"
Sometimes it works, but in the database the value "name" is "NULL"
i dont know where is the error. so i need some help.
My db:
CREATE TABLE users(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(200)
)ENGINE=INNODB;
My Form.js code:
import React from 'react'
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { name: '' };
}
handleChange = (event) => {
this.setState({[event.target.name]: event.target.value});
}
handleSubmit = (event) => {
alert('A form was submitted: ' + this.state);
fetch('/store-data', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
// We convert the React state to JSON and send it as the POST body
body: JSON.stringify(this.state)
}).then(function(response) {
console.log(response)
return response.json();
});
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} name="name" onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default MyForm;
And my server.js code:
const express = require("express");
const bodyParser = require('body-parser');
const cors = require("cors");
const mysql = require('mysql');
const app = express();
app.use(cors());
// parse application/json
app.use(bodyParser.json());
//create database connection
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'conex'
});
//connect to database
conn.connect((err) => {
if (err) throw err;
console.log('Mysql Connected...');
});
//add new user
app.post('/store-data', (req, res) => {
let data = { name: req.body.name };
let sql = "INSERT INTO users SET ?";
let query = conn.query(sql, data, (err, results) => {
if (err) throw err;
res.send(JSON.stringify({ "status": 200, "error": null, "response": results }));
});
});
app.listen(3000, () => {
console.log("Server running successfully on 3000");
});
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");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
next();
});
I'm trying to do simple form.

server crashed down when I was trying to login the data for testing validation

I was trying to input wrong data to see how the server getting data from the database and responding to the client if there is any incorrect like wrong username/password or username does not exist. It worked perfectly and responded for 1 to 2 times until the third time the crash happened:
Cannot set headers after they are sent to the client
ERR_CONNECTION_REFUSED``
Here is my server-side:
const express = require("express");
const router = express.Router();
const { Users } = require("../models");
const bcrypt = require('bcryptjs');
router.post("/", async (req, res) => {
const {username, password, phone, email} = req.body;
const user = await Users.findOne({ where: {username: username}});
if(user) {
res.json({ error: "User is unavailable"});
} else {
bcrypt.hash(password, 10).then((hash) => {
Users.create({
username: username,
password: hash,
phone: phone,
email: email,
});
res.json("SUCCESS");
});
};
});
router.post("/login", async (req, res) => {
const { username, password } = req.body;
const user = await Users.findOne({ where: { username: username } });
if (!user) res.json("User Doesn't exist");
bcrypt.compare(password, user.password).then((match) => {
if (!match) res.json("Wrong Username or Password");
res.json("YOU LOGGED IN");
});
});
module.exports = router;
and Here is my client side:
import {FontAwesomeIcon} from '#fortawesome/react-fontawesome';
import {faUser, faLock, faEye, faEyeSlash} from '#fortawesome/free-solid-svg-icons';
import { BiUser } from "react-icons/bi";
import {Link} from 'react-router-dom';
import { useState } from 'react';
import axios from 'axios';
function Register() {
const [username, setUsername] = useState("");
const [password, setPassword]= useState("");
const [type, setType] = useState("password");
const [icon, setIcon] = useState(faEye);
const handleShowHidePass = () => {
let currentType = type === "password" ? "text" : "password";
let currentIcon = icon === faEye ? faEyeSlash : faEye;
setType(currentType);
setIcon(currentIcon);
}
const login = e => {
e.preventDefault();
axios.post ("http://localhost:3001/auth/login", {
username: username,
password: password,
}).then((res) =>{
console.log(res.data);
});
};
return(
<div className="right">
<span className="title"><BiUser className="tilteIcon"/></span>
<form onSubmit={login} >
<div className="formInput">
<span className="icon"><FontAwesomeIcon icon={faUser}/></span>
<input
type="text"
className="username"
value={username}
placeholder="Username"
onChange={(e) => {
setUsername(e.target.value)
}}
/>
</div>
<div className="formInput">
<span className="icon"><FontAwesomeIcon icon={faLock}/></span>
<input
type={type}
className="password1"
value={password}
placeholder="Password"
onChange={(event) => {
setPassword(event.target.value)
}}
/>
<span className="show"><FontAwesomeIcon icon={icon} onClick={handleShowHidePass}/></span>
</div>
<div className="formInput">
<button type="submit">Sign Up</button>
</div>
<div className="login">
<Link to="/register" style={{textDecoration: 'none'}}>I already have an account!</Link>
</div>
</form>
</div>
);
}
export default Register;
use return with this line if (!user) return res.json("User Doesn't exist");
your code is executing further after sending the response

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

I can't fetch react form

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.

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;