400 Bad Request Cloudinary Upload Error in React + Nodejs + mySQl - mysql

I am currently building a Full stack Web App with React, MySQL, Nodejs, Express and Cloudinary, I am having issues uploading to Cloudinary, for security reasons, I didnt post my true upload_preset here
The code below is my React code:
import React, { useState } from 'react';
import "./Upload.css";
import Axios from 'axios';
function Upload() {
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [image, setImage] = useState([]);
const upload = () => {
const formData = new FormData();
formData.append("file", image[0]);
formData.append("upload_preset", "fzqyat");
Axios.post(`https://api.cloudinary.com/v1_1/williampepple/image/upload`, formData).then((response) => {
const fileName = response.data.public_id;
Axios.post("http://localhost:3001/upload", {
title: title,
description: description,
image: fileName});
});
;}
return (
<div className="Upload">
<h1>Create a Post</h1>
<div className="UploadForm">
<input type="text" placeholder="Title..."
onChange={(event) =>{setTitle(event.target.value);
}}
/>
<input type="text" placeholder="Description..."
onChange={(event) =>{setDescription(event.target.value);
}}
/>
<input type="file" onChange={(e) =>setImage(e.target.value)}/>
<button onClick={upload}>Upload</button>
</div>
</div>
)
}
export default Upload
Below is my Index.js file in my Nodejs Folder:
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors());
app.use(express.json())
const userRoute = require('./Routes/User');
app.use("/user", userRoute);
const uploadRoute = require('./Routes/Upload');
app.use("/upload", uploadRoute);
app.listen(3001, (req, res) => {
console.log("server running..");
});
Below is my Upload route file:
const express = require('express');
const router = express.Router();
const db = require('../config/db')
router.post('/', (req, res)=> {
const title = req.body.title
const description = req.body.description
const image = req.body.image
db.query(
"INSERT INTO Uploads(title, description, image) VALUES (? , ? , ?);", [title, description, image],
(err, results)=>{
console.log(err);
res.send(results);
}
);
});
module.exports = router;

Related

How to import csv to MySQL using ReactJs

I'm trying to upload csv file into mysql workbench, what I'm trying to figure out is when I upload the csv file, the first column of the excel will be the header of the table in workbench.
Front end
const Home = () => {
const [file, setFile] = useState(null);
const handleFileInput = (event) => {
setFile(event.target.files[0]);
};
const handleUpload = async () => {
const formData = new FormData();
formData.append("file", file);
try {
const res = await fetch("http://localhost:5000/api/upload", {
method: "POST",
body: formData,
});
const data = await res.json();
console.log(data);
} catch (error) {
console.error({message:error.message});
}
};
return (
<div>
<input type="file" onChange={handleFileInput} />
<button onClick={handleUpload}>Upload</button>
</div>
)
}
export default Home
index.js
import express from 'express';
import cors from 'cors';
import mysql from 'mysql2/promise';
import csv from 'csv-parser'
const PORT = 5000
const app = express();
app.use(express.json());
app.use(cors())
app.post('/api/upload', async (req, res) => {
const { file } = req.files;
const results = [];
try {
const connection = await mysql.createConnection({
host: "localhost",
user: "root",
password: "admin",
database: "e-learning"
});
fs.createReadStream(file.path)
.pipe(csv())
.on("data", (data) => results.push(data))
.on("end", async () => {
const columns = Object.keys(rows[0]).map(column => `\`${column}\` VARCHAR(255)`);
const tableName = `${filePath}`;
const createTableSql = `CREATE TABLE \`${tableName}\` (${columns.join(", ")})`;
await connection.query(createTableSql);
const insertDataSql = `INSERT INTO \`${tableName}\` (${Object.keys(rows[0]).map(column => `\`${column}\``).join(", ")}) VALUES ?`;
const data = rows.map(row => Object.values(row));
await connection.query(insertDataSql, [data]);
console.log(`Table "${tableName}" created and data inserted successfully.`);
});
} catch (error) {
console.log(error)
}
})
app.listen(PORT, () =>{
console.log(`Listening to port http://localhost:${PORT}`)
})
This is the error i'm receiving

How to send form data together with file to mysql

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

How to upload image/file to mysql but display it as file not as BLOB

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

error adding data to mysql column and all column counted as NULL

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

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;