how can i post data from reactjs form to mysql database - mysql

How can I send this data to database MySQL from a reactjs form? I'm a beginner in reactjs and I'm tired of trying.
In the back-end I use nodejs, express, and cors, so if u can tell me how because I have to finish this work.
The console returns GET Localhost 404 Not Found.
This is what I do but I don't know there is a better way to make it.
import React, { Component } from 'react'
import { Table,Button,
Modal,ModalHeader,
ModalBody,ModalFooter,
Label,Input,Form } from 'reactstrap';
export default class Db1 extends Component {
state = {
users: [],
newUserData: {
nom: '',
prenom: '',
adresse: '',
email: ''
},
newUserModal:false,
}
componentDidMount() {
this.getUsers();
}
getUsers = () => {
fetch('http://localhost:4000/users')
.then(response => response.json())
.then(response => this.setState({ users: response.data}))
.catch(err => console.error(err))
}
addUser = () => {
let { nom,prenom,adresse,email } = this.state.newUserData;
fetch(`http://localhost:4000/users/add?
nom=${nom}&prenom=${prenom}&adresse=${adresse}&email=${email}`,{
method: 'POST',
body: JSON.stringify({
nom: this.nom,
prenom: this.prenom,
adresse: this.adresse,
email: this.email
}),
headers: {"Content-Type": "application/json"}
})
.then(this.getUsers)
.catch(err => console.error(err))
this.setState({newUserModal:false});
console.log(this.newUserData) // return undefined
}
toggleNewUserModal = () => {
this.setState({
newUserModal: ! this.state.newUserModal
});
}

const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser')
const app = express();
// Connection Mysql
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'dbusers',
});
connection.connect(err => {
if (err) {
console.log("conection error");
return err;
}
});
// Connection Express Body-Parser Cors
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello from the users server')
});
// Selectionner Tous Les Utilisateurs
app.get('/users', (req, res) => {
const selectQuery = 'SELECT * FROM userslist';
connection.query(selectQuery, (err, results) => {
if(err) {
res.send(err)
}
else {
res.json({data: results})
}
});
});
// Ajouter Un Nouveau Utilisateur
app.post('/users/add', (req, res) => {
let nom = req.body.nom;
let prenom = req.body.prenom;
let adresse = req.body.adresse;
let email = req.body.email;
let insertQuery ="INSERT INTO userslist SET ?"
const user={nom,adresse,prenom,email}
connection.query(insertQuery,user, (err, results) => {
if(err) {
console.log("insert error");
res.send(err)
}
else {
res.send({ error: false, data: results, message: 'user has been
updated successfully.' });
}
});
});
// Editer Un Nouveau Utilisateur
app.post('/users/update/:id', (req, res) => {
let id = req.params.id;
let nom = req.body.nom;
let prenom = req.body.prenom;
let adresse = req.body.adresse;
let email = req.body.email;
let updateQuery =`UPDATE userslist SET ? WHERE id=${id}`
const user={nom,adresse,prenom,email}
connection.query(updateQuery,user, (err, results) => {
if(err) {
console.log("insert error");
res.send(err)
}
else {
res.send({ error: false, data: results, message: 'user has been
updated successfully.' });
}
});
});
// Suprimer un Utilisateur
app.post("/users/delete/:id", (req, res) => {
let id = req.params.id;
let sql = 'DELETE FROM userslist WHERE id=?';
connection.query(sql, [id], (error, results, fields) => {
if (error)
console.error(error.message);
console.log("Deleted Row(s):", results.affectedRows);
res.json({error:false,data: results})
});
});
app.listen(4000, () => {
console.log('Users server worked on port 4000...')
});

Related

{"code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false}

I am new to MySQL, and I am having difficulties in getting my data from MySQL database.
import express from 'express';
import mysql from 'mysql';
const app = express();
const db = mysql.createConnection({
host:"localhost",
user:"root",
password:"2000",
database: "test"
})
app.get('/', (req, res) => {
res.json('hello this is backend')
})
app.get('/books', (req, res) => {
const q = "SELECT * FROM books"
db.query(q, (err, data) => {
if(err) {
return res.json(err)
}
else{
return res.json(data)
}
})
})
app.listen(8800, () => {
console.log('Connected to backend server...');
});
as it gives following error on localhost:8800/books/
{"code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false}
any help would be valuable :)

Cannot set headers after they are sent to the client error when add code to redirect another page

I have login page and signup page. when a user want register account and register is successful, I want to redirect him to signin.html page. however, nothing I've tried have worked so far. I always get the error "Cannot set headers after they are sent to the client" when I add this code "res.redirect('http://localhost:3000/signin.html')". here is my code
signup.html
const form = document.getElementById('reg-form')
form.addEventListener('submit', registerUser)
async function registerUser(event){
event.preventDefault()
const username = document.getElementById('user').value
const password = document.getElementById('password').value
const password_confirmation = document.getElementById('password_confirmation').value
const phone = document.getElementById('tel').value
const result = await fetch('/register',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username,
password,
password_confirmation,
phone
})
}).then((res) => res.json())
if (result.status === 'ok') {
alert('success')
}else {
alert (result.error)
}
}
and here is server.js
const express = require('express')
const path = require ('path')
const mongoose = require ('mongoose')
const User = require ('./model/user')
const bodyParser = require('body-parser')
const bcrypt = require ('bcryptjs')
const jwt = require ('jsonwebtoken')
const JWT_SECRET = 'lkjlfg%nlnkllkj#R%##%#&bgkj3nskk2cnklvdfsflkjlkjf98748'
const port =3000
mongoose.connect('mongodb://localhost:27017/login-app-db', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
const app = express()
app.use('/', express.static(path.join(__dirname, '../code FE/')))
app.use(bodyParser.json())
// app.post('/api/change-password', (req, res) => {
// const { token } = req.body
// const user = jwt.verify(token, JWT_SECRET)
// console.log()
// })
app.post('/signin', async (req, res) => {
const { username, password } = req.body
const user = await User.findOne({ username }).lean()
console.log(password)
if (!user) {
return res.json({status: 'error', error: 'Invalid username/password'})
}
if (await bcrypt.compare('password', user.password)) {
// the username, password combination is successfully
const token = jwt.sign({
id: user._id,
username: user.username
},
JWT_SECRET
)
return res.json({status: 'ok', data: token})
}
return res.json({status: 'error', error: 'Invalid username/password'})
})
app.post('/register', async (req, res) => {
console.log(req.body)
const { username, password: plainTextPassword, password_confirmation: someOtherPlaintextPassword, phone} = req.body
if (!username || typeof username !== 'string') {
return res.json({ status: 'error', error: 'Invalid username'})
}
if (!plainTextPassword || typeof plainTextPassword !== 'string') {
return res.json({ status: 'error', error: 'Invalid password'})
}
const password = await bcrypt.hash('password', 10)
const password_confirmation = await bcrypt.hash('password_confirmation', 10)
try {
const response = await User.create({
username,
password,
password_confirmation,
phone
})
console.log('user created successfully: ', response)
res.redirect('http://localhost:3000/signin.html')
}catch(error){
if (error.code === 11000) {
return res.json({ status: 'error', error: 'username already in use'})
}
throw error
}
res.json({status: 'ok'})
})
app.listen(port, () => {
console.log(`Example app listening on port http://localhost:${port}`)
})

MY SQL Sequelize Unique Value not working as intended

I am trying to code a website to work with ReactJS, NodeJs and MySQL.
I have been using Sequelize and it works but i realised that it allows all usernames even those that are used.
i set the value to be Unique in the JS file.
I have followed this website (https://sequelize.org/docs/v6/core-concepts/validations-and-constraints/) but to no success.
module.exports = (sequelize,DataTypes) =>{
const Users = sequelize.define("Users", {
username:{
type: DataTypes.TEXT,
allownull: false,
unique: true
},
userpass:{
type: DataTypes.STRING,
allownull: false,
},
usergroup:{
type: DataTypes.STRING,
allownull: false,
},
});
return Users;
}
The code i am running
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const mysql = require('mysql2');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "testschema"
})
const db = require('./models');
// Routers
const userRouter = require('./routes/user-routes');
app.use("/users", userRouter);
app.post('/testing', (req, res) => {
console.log("testing route");
console.log(req.body);
res.send("Testing Route");
})
app.post('/login', async (req, res) => {
const username = req.body.username
const userpass = req.body.userpass
console.log("Line 9", req.body)
console.log("backend triggered");
const loginInfo = await new Promise((resolve, reject) => {
connection.query("SELECT * FROM users WHERE username = ? AND userpass = ?", [username, userpass], (err, result) => {
if (err) {
console.log(err)
}
else {
if (result.length > 0) {
console.log("Success" + result);
resolve(result)
}
else {
console.log("Wrong username/password")
}
}
})
});
console.log(loginInfo)
})
;
app.post('/register', async (req, res) => {
const username = req.body.username
const userpass = req.body.userpass
console.log("Line 83", req.body)
console.log("backend triggered");
const registerInfo = await new Promise((resolve, reject) => {
connection.query("INSERT INTO users (username, userpass,createdAt,updatedAt) VALUES (?,?,0,0)", [username, userpass], (err, result) => {
if (err) {
console.log(err)
}
})
});
console.log(registerInfo)
})
connection.connect((err) => {
if (err) {
console.log("Error occurred", err);
} else {
console.log("Connected to MySQL Server");
}
});
db.sequelize.sync().then(() => {
app.listen(8000, () => {
console.log("Server is up on port 8000");
});
});
This is what i get in the backend
Connected to MySQL Server
Executing (default): CREATE TABLE IF NOT EXISTS `Users` (`id` INTEGER NOT NULL auto_increment , `username` TEXT UNIQUE, `userpass` VARCHAR(255), `usergroup` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `Users` FROM `testschema`
Server is up on port 8000
Line 83 { username: 'blueflag', userpass: 'blueflag' }
backend triggered

How can i resolve 'Cannot set headers after they are sent to the client'

How can I resolve Cannot set headers after they are sent to the client:
app.js
var express = require('express');
var session = require('express-session');
var mongoose = require('mongoose');
var app = express();
var ejs = require('ejs');
var port = 3000;
var bodyParser = require('body-parser');
var mongoDB = "mongodb://localhost:27017/vinavdb";
app.set('views', __dirname + '/admin') app.engine('html', ejs.renderFile);
app.set('view engine', 'ejs');
app.set('trust proxy', 1);
app.use(session({
secret: 'dsghbrtdfhbdfg64545TRYFFHGGJNN',
resave: false,
saveUninitialized: true
}))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var sess;
mongoose.Promise = global.Promise;
mongoose.connect(mongoDB, {
useNewUrlParser: true
});
var nameSchema = new mongoose.Schema({
firstname: String,
lastname: String,
email: String,
password: String
});
var User = mongoose.model("User", nameSchema);
app.get("/", (req, res) => {
sess = req.session;
if (sess.email) {
res.redirect("/admin");
} else {
res.sendFile(__dirname + "/index.html");
}
});
app.get("/login", (req, res) => {
res.sendFile(__dirname + "/login.html");
});
app.post("/addname", function(req, res) {
var myData = new User(req.body);
User.findOne({
email: req.body.email
}, function(err, resv) {
if (resv == null) {
myData.save().then(item => {
res.send("Name saved to database")
}).catch(err => {
res.status(400).send("Unable to save to database");
});
res.send("ThankYou For your Registration")
} else if (resv.email == req.body.email) {
res.send("Email is already registered");
} else {
res.send("Srry data is not allowed");
}
});
});
app.post("/login", function(req, res, next) {
User.findOne({
email: req.body.email
}, function(err, vals) {
if (vals == null) {
res.end("Invalid Logins");
} else if (vals.email == req.body.email && vals.password == req.body.password) {
sess = req.session;
sess.email = req.body.email;
res.redirect('/admin');
} else {
res.send("Srry data is not allowed");
}
});
});
app.route('/admin').get(function(req, res, next) {
sess = req.session;
if (sess.email) {
res.send(__dirname + "/admin/index.html");
} else {
res.write('Please login first.');
}
})
app.listen(port, () => {
console.log("Server listening on port " + port);
});
Cause of your error : You are trying to send a response of a single request twice.
One request have one response.
Once response is send, you cannot send it again for the same request.In your /addname API, You are trying to send response twice. So remove one.
Here .save() is asynchronous function so node will not wait and execute
res.send("ThankYou For your Registration") first and later once record will be saved it will try to send res.send("Name saved to database") so you are getting error here.
app.post("/addname", function(req, res) {
var myData = new User(req.body);
User.findOne({
email: req.body.email
}, function(err, resv) {
if (resv == null) {
myData.save().then(item => {
console.log("Name saved to database")
res.send("ThankYou For your Registration")
}).catch(err => {
res.status(400).send("Unable to save to database");
});
} else if (resv.email == req.body.email) {
res.send("Email is already registered");
} else {
res.send("Srry data is not allowed");
}
});
});
After you execute a res.send you cannot call it again in the same request, it only allows one response per request. In your code, I think in this part it can happens:
if (resv == null) {
myData.save().then(item => {
res.send("Name saved to database")
}).catch(err => {
res.status(400).send("Unable to save to database");
});
res.send("ThankYou For your Registration")
}
In this if, when you are saving myData you are sending a response, but asynchronously you already sent another response previously ("ThankYou For your Registration").
Hope it helps

How do I pass mysql database content to a different page?

I am trying to display my database content to an ejs web page. However, I am running into a problem when trying to pass the content between pages.
I have a JavaScript page "store.js" which has the server running:
store.js-
var express = require('express');
var dbcon = require('./app/db/databaseconnection');
//var path = require('path');
//dbcon.connection;
var app = express();
var router = express.Router();
dbcon.connect();
console.log(dbcon.getproducts());
//var filepath = path.join(__dirname, '../../views/')
var filepath = __dirname + '/views/';
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use('/', router);
router.get('/', (request, response) => response.render(filepath + 'index', { page_name: 'home' }));
router.get('/store', (request, response) => response.render(filepath + 'store', { page_name: 'store' }));
router.get('/about', (request, response) => response.render(filepath + 'about', { page_name: 'about' }));
router.get('/contact', (request, response) => response.render(filepath + 'contact', { page_name: 'contact' }));
router.get('/build', (request, response) => response.render(filepath + 'build/build'));
router.get('/learn', (request, response) => response.render(filepath + 'learn/learn'));
app.use('*', (request, response) => response.render(filepath + '404', { page_name: '404' }));
app.listen(3000, () => console.log("Server running at Port 3000"));
Then I have a JavaScript page which includes the database connection:
databaseconnection.js-
var mysql = require('mysql');
var connection = mysql.createConnection(conObject = {
host: "localhost",
user: "root",
password: "LOTOS123l",
database: "dbComputerStore"
});
module.exports = {
connect: () =>
{
connection.connect((error) => {
if (error) throw error;
console.log(conObject.database + " connected!");
});
},
// The display method prints the returned result to the console.
// Change this to return the result. Maybe a toString() ?
getproducts: () => {
/*var result = */connection.query('SELECT * FROM products', (error, result) => {
return result;
//return result;
// console.log(result);
// How to get certain properties
// console.log(result[0].brand);
// console.log(result[0].series);
// console.log(result[0].model);
});
//return result.result;
},
createdb: () => {
},
createtable: () => {
},
populatetable: () => {
}
}
So on the store.js page I have the console.log(dbcon.getproducts()); Which I was hoping would display the database content of the "products" table. However I keep getting undefined. Basically, I can't get it to pass from the database connection page to the store.js page.
If I get this to work, my next step would be to find a way to display the products table to an ejs page. I've been trying to solve this for a while now so any help would be appreciated! Thank You!
Following up my comments, here's how you can modify databaseconnection.js module to use a connection pool and return query results via Promises:
Note: the code is mostly untested
const mysql = require("mysql");
const pool = mysql.createPool({
connectionLimit: 10, // adjust this according to your needs
host: "localhost",
user: "root",
password: "LOTOS123l",
database: "dbComputerStore"
});
module.exports = {
// you don't need the connect method anymore
getProducts: () => new Promise((resolve, reject) => {
pool.query("SELECT * FROM products", (error, results, fields) => {
if (error) {
reject(error);
} else {
resolve(results);
}
});
}),
// ...
};
then in store.js, you can do:
const dbcon = require('./app/db/databaseconnection');
dbcon.getProducts()
.then(results => {
console.log(results);
})
.catch(err => {
console.error(err);
});
// or you could use async/await syntax:
const asyncFn = async () => {
try {
const results = await dbcon.getProducts();
console.log(results);
} catch (ex) {
console.error(err);
}
};
asyncFn();