I'm working on a project for my portfolio and decided I would do the registration page and backend first so that can be out of the way. I followed a tutorial with nodejs and mysql but I'm getting an error saying TypeError: Converting circular structure to JSON --> starting at object with constructor 'HTMLInputElement' | property '__reactFiber$g76m1cpwrsr' -> object with constructor 'FiberNode' --- property 'stateNode' closes the circle. I can't tell exactly where is error might be originating from or what is causing this issue. Any help would be appreciated
Registration page
import React, { useState } from "react";
import "../Styling/Register.css";
import axios from "axios";
function Register() {
const [userName, setUsername] = useState("");
const [userEmail, setUserEmail] = useState("");
const [userPassword, setUserPassword] = useState("");
const [userSubject, setUserSubject] = useState("");
const [account_type, setAcc_Type] = useState("");
const create_user = () => {
axios
.post("http://localhost:3001/register", {
userID: 1001,
userName: userName,
Email: userEmail,
password: userPassword,
subject: userSubject,
acc_type: account_type,
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
};
return (
<div className="form">
<input
type="text"
placeholder="FULL NAME"
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="text"
placeholder="Email"
onChange={(e) => setUserEmail(e.target.value)}
/>
<input
type="text"
placeholder="Password"
onChange={(e) => setUserPassword(e.target.value)}
/>
<input
type="text"
placeholder="Field/Subject"
onChange={(e) => setUserSubject(e.target.value)}
/>
<input
type="text"
placeholder="Tutor/Student"
onChange={(e) => setAcc_Type(e.target.value)}
/>
<button onClick={create_user}>Register</button>
</div>
);
}
export default Register;
My server side script in nodejs
const express = require('express');
const mysql = require('mysql');
const cors = require('cors');
const app = express();
app.use(express.json())
app.use(cors());
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'tutor_locator'
});
app.post('/register', (req, res) => {
const userID = req.body.userID;
const userName = req.body.userName;
const Email = req.body.userEmail;
const password = req.body.userPassword;
const subject = req.body.userSubject;
const acc_type = req.body.account_type;
db.query(
'INSERT INTO users(User_ID, User_Name, User_Email, user_Password, User_Subject, Accout_Type) VALUES (?,?,?,?,?,?)',
[userID, userName, Email, password, subject, acc_type],
(err, result) => {
console.log(res);
}
)
})
app.listen(3001, () => {
console.log('server started');
});
Related
Hello so i'm working on project which user can input data and upload file through form. I made this project with react js, node, express, and using mysql as database. Im currently having a problem to input name and upload file simultaneously. How to uplaod the data and file together with one button. sry for bad english
App.js
import React,{ useState, useEffect} from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [invoice, setInvoice] = useState("");
const [date, setDate] = useState ("");
const [currency, setCurrency] = useState ("IDR");
const [amount, setAmount] = useState("");
const [title, setTitle] = useState("");
const [path, setPath] = useState("");
const [attachment, setAttachment] = useState("");
const [dataList, setDataList] = useState([]);
useEffect(() => {
Axios.get('http://localhost:3001/api/get').then((response)=> {
setDataList(response.data);
})
})
const submitData = () => {
Axios.post('http://localhost:3001/api/insert', {
Invoice_No: invoice,
Invoice_Date: date,
Curr: currency,
Amount: amount,
Supplier: title,
Path: path
})
}
return (
<div className="App">
<p>CRUD Applicaiton</p>
<div className="formControl">
<label>Invoice No</label>
<input type="number" onChange={(e)=> {
setInvoice(e.target.value);
}} />
<label>Invoice Date</label>
<input type="date" onChange={(e)=> {
setDate(e.target.value);
}} />
<label>Currency</label>
<select onChange={(e)=> {
setCurrency(e.target.value);
}}>
<option value="IDR">IDR</option>
<option value="USD">USD</option>
<option value="YEN">YEN</option>
</select>
<label>Amount</label>
<input type="number" onChange={(e)=> {
setAmount(e.target.value);
}} />
<label>Title</label>
<input type="text" onChange={(e)=> {
setTitle(e.target.value);
}} />
<button onClick={submitData}>Add Data</button>
<button type='reset'>Reset</button>
</div>
<div>
<form method='POST' encType='multipart/form-data' action='http://localhost:3001/api/upload'>
<input type="file" name="DocumentFile" />
<button>ADD to DB</button>
</form>
</div>
</div>
);
}
export default App;
index.js
const express = require('express');
const fs = require('fs');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
const mysql = require('mysql');
const exphbs = require('express-handlebars');
const multer = require("multer")
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "work"
});
const upload = multer({storage:multer.memoryStorage()});
app.use(cors());
app.use(express.json() || express.static(".public") || express.static(".upload"));
app.use(bodyParser.urlencoded({extended: true}));
app.get("/api/get", (req, res) => {
const sqlSelect= "SELECT * FROM invoice"
db.query(sqlSelect, (err, result)=>{
res.send(result);
});
})
app.post("/api/insert", (req, res) => {
const Invoice_No = req.body.Invoice_No
const Invoice_Date = req.body.Invoice_Date
const Currency = req.body.Curr
const Amount = req.body.Amount
const Title = req.body.Supplier
const sqlInsert = "INSERT INTO invoice(Invoice_No, Invoice_Date, Curr, Amount, Supplier) VALUES (?,?,?,?,?)"
db.query(sqlInsert, [Invoice_No, Invoice_Date, Currency, Amount, Title], (err, result)=>{
console.log(err)
});
})
app.post("/api/upload", upload.single('DocumentFile'), (req, res) => {
const Path = req.file.buffer.toString('base64')
q = "INSERT INTO invoice (Path) VALUES (?)"
db.query(q, [Path], (err, result) => {
console.log(Path)
})
})
app.listen(3001, ()=> {
console.log('running on port 3001')
});
Hello so i wanna try to upload data from form to mysql server using react as frontend and node.js as backend.
But i want to display/show the uploaded file as pdf not as BLOB. Is there a way to display the document/file as file in mysql so you can download the file easir or do you have to convert it in javascript? Thanks.
App.js
function App() {
const [employeeName, setName] = useState("");
const [employeeAge, setAge] = useState("");
const [employeePosition, setPosition] = useState("");
const [employeeSalary, setSalary] = useState("");
const [employeeFile, setFile] = useState();
const [dataList, setDataList] = useState([]);
const submitData = () => {
Axios.post('http://localhost:3001/api/insert', {
Name: employeeName,
Age: employeeAge,
Position: employeePosition,
Salary: employeeSalary,
Image: employeeFile
})
if(employeeName && employeeAge && employeePosition && employeeSalary && employeeFile != null){
alert("Berhasil ")
}else{
alert("Masukan Input")
}
}
return (
<div className="App">
<p>CRUD Applicaiton</p>
<div className="formControl">
<form>
<label>Name</label>
<input type="text" onChange={(e)=> {
setName(e.target.value);
}} />
<label>Age</label>
<input type="number" onChange={(e)=> {
setAge(e.target.value);
}} />
<label>Position</label>
<input type="text" onChange={(e)=> {
setPosition(e.target.value);
}} />
<label>Salary</label>
<input type="number" onChange={(e)=> {
setSalary(e.target.value);
}} />
<div className='fileUpload'>
<input type="file" onChange={(e)=> {setFile(e.target.value)}} />
</div>
<button onClick={submitData}>Add Data</button>
<button type='reset'>Reset</button>
</form>
</div>
</div>
);
}
export default App;
index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "coba"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.post("/api/insert", (req, res) => {
const Name = req.body.Name
const Age = req.body.Age
const Position = req.body.Position
const Salary = req.body.Salary
const Image = req.body.Image
const sqlInsert = "INSERT INTO employee (Name, Age, Position, Salary, Image) VALUES (?,?,?,?,?)"
db.query(sqlInsert, [Name, Age, Position, Salary, Image], (err, result)=>{
console.log(result)
});
})
app.listen(3001, ()=> {
console.log('running on port 3001')
});
Hello so i started the project using react, node js, and mysql.
My goal is to create a form in frontend and want to add the data in form to mysql database.
But after submiting there is a error'INSERT INTO employee (Name, Age, Position, Salary) VALUES (NULL,NULL,NULL,NULL)'.
The problem here is in all column it says "cannot be null". How do i solve this.
App.js
import React,{ useState, useEffect} from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [employeeName, setName] = useState("")
const [employeeAge, setAge] = useState("")
const [employeePosition, setPosition] = useState("")
const [employeeSalary, setSalary] = useState("")
const submitData = () => {
Axios.post('http://localhost:3001/api/insert', {
Name: employeeName,
Age: employeeAge,
position: employeePosition,
Salary: employeeSalary
}).then(()=>{
alert('Berhasil')
})
}
return (
<div className="App">
<p>CRUD Applicaiton</p>
<div className="formControl">
<label>Name</label>
<input type="text" onChange={(e)=> {
setName(e.target.value);
}} />
<label>Age</label>
<input type="number" onChange={(e)=> {
setAge(e.target.value);
}} />
<label>Position</label>
<input type="text" onChange={(e)=> {
setPosition(e.target.value);
}} />
<label>Salary</label>
<input type="number" onChange={(e)=> {
setSalary(e.target.value);
}} />
<button type="submit" value="Submit" onClick={submitData}>Add Data</button>
<button type="reset" value="Reset">Reset</button>
</div>
</div>
);
}
export default App;
index.js (backend)
const express = require('express');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "coba"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.post("/api/insert", (req, res) => {
const Name = req.body.employeeName
const Age = req.body.employeeAge
const Position = req.body.employeePosition
const Salary = req.body.employeeSalary
const sqlInsert = "INSERT INTO employee (Name, Age, Position, Salary) VALUES (?,?,?,?)"
db.query(sqlInsert, [Name, Age, Position, Salary], (err, result)=>{
console.log(err)
});
})
app.listen(3001, ()=> {
console.log('running on port 3001')
});
You need to change your backend code.
Try once with the following code:
app.post("/api/insert", (req, res) => {
const Name = req.body.Name
const Age = req.body.Age
const Position = req.body.position
const Salary = req.body.Salary
const sqlInsert = "INSERT INTO employee (Name, Age, Position, Salary) VALUES (?,?,?,?)"
db.query(sqlInsert, [Name, Age, Position, Salary], (err, result)=>{
console.log(err)
});
})
How i can prevent duplicate record input especially email and student number And show the message if the registration is accepted or it has duplicate record?
It accept data and when a set the email and the student number unique in the MySQL db it will not accept data but their is no message. It only show message in the terminal of visual studio that the email and student number is unique
Front end
import React from 'react'
import { useState } from 'react';
import Axios from 'axios';
import { useNavigate} from 'react-router-dom'
function Register() {
let navigate= useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [student_num , setStudnum] = useState(0);
const [RegisterStatus, setRegisterStatus] = useState("");
const [studentList, setStudentList] = useState([])
const addStudent = ( ) =>{
Axios.post("http://localhost:3001/create", {
email: email,
password: password,
student_num : student_num ,
}).then(()=>{
console.log("sucess")
});
};
return (
<form>
<div className="information">
<div className="App">
<label>Email:</label>
<input type="text" onChange={(event) => {
setEmail(event.target.value);
}} required />
<label>Password:</label>
<input type="password" onChange={(event) => {
setPassword(event.target.value);
}} required/>
<label>Student Number:</label>
<input type="number" onChange={(event) => {
setStudnum(event.target.value);
}}required/>
This is the MySQL connection / backend
app.post("/create", (req, res) => {
const email = req.body.email;
const password = req.body.password;
const student_num = req.body.student_num;
db.query(
"INSERT INTO student (email,passwordstudent_num) VALUES (?,?,?)",
[
email,
password,
student_num,
],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send("Values Inserted");
}
}
);
});
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