Data from my react front end not getting to mysql database - javascript

I have a react front-end, node server, and MySQL database. I'm making use of express server and Axios for my post request. The code doesn't appear to have an error, also in the console and network in chrome. However, no data gets to my database. I'll really appreciate the help. Here are my codes;
Client
import React, { useState } from 'react';
import './register.css';
import {Link} from 'react-router-dom';
import Image from '../../assets/Image.png';
import Axios from 'axios';
const Register = () => {
const [uploadReq, setUploadReq] = useState('')
const [usernameReq, setUsernameReq] = useState('')
const [fullnameReq, setFullnameReq] = useState('')
const [emailReq, setEmailReq] = useState('')
const [passwordReq, setPasswordReq] = useState('')
const registration = () => {
Axios.post("http://localhost3000/register",{
upload: uploadReq,
username: usernameReq,
fullname: fullnameReq,
email: emailReq,
password: passwordReq,
}).then((response) => {
console.log(response);
});
};
return (
<div className='register section__padding'>
<div className="register-container">
<h1>register</h1>
<p className='upload-file'>Upload Profile pic</p>
<div className="upload-img-show">
<img src={Image} alt="banner" />
<p>browse media on your device</p>
</div>
<form className='register-writeForm' autoComplete='off' >
<div className="register-formGroup">
<label>Upload</label>
<input type="file" className='custom-file-input'
onChange={(e) => {
setUploadReq(e.target.value);
}}
/>
</div>
<div className="register-formGroup">
<label>Full Name</label>
<input type="text" placeholder='Name'
onChange={(e) => {
setFullnameReq(e.target.value);
}}
/>
</div>
<div className="register-formGroup">
<label>Username</label>
<input type="text" onChange={(e) => {
setUsernameReq(e.target.value);
}}placeholder='Username' />
</div>
<div className="register-formGroup">
<label>Email</label>
<input type="email" placeholder='Email'
onChange={(e) => {
setEmailReq(e.target.value);
}}
/>
</div>
<div className="register-formGroup">
<label>Password</label>
<input type="text" onChange={(e) => {
setPasswordReq(e.target.value);
}} placeholder='Password' />
</div>
<div className="register-button">
<button className='register-writeButton' onClick={registration}>register</button>
<Link to="/login">
<button className='reg-login-writeButton' >Login</button>
</Link>
</div>
</form>
</div>
</div>
)
};
export default Register;
Server
const express = require("express");
const app = express();
const mysql = require("mysql");
const cors = require("cors");
app.use(express.json());
app.use(cors());
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "xyz",
database: "nftdatabase",
});
app.post('/register', (req, res) => {
const upload = req.body.upload
const Fullname = req.body.fullname
const Username = req.body.username
const Email = req.body.email
const Password = req.body.password
db.query("INSERT INTO user (upload, fullname, username, email, password) VALUES (?,?,?,?,?)",
[upload, Fullname, Username, Email, Password],
(err, result) => {
console.log(err);
});
});
app.listen(3001, () => {
console.log("running on port 3001");
});

Your server is running on PORT 3001 whereas from your client you are calling the API endpoint on PORT 3000. Have you used proxy in client side. Have you added this line in package.json file?
"proxy": "http://localhost:3001"

Related

React + Nodemailer: the email gets sent but it opens a new window and as well, how can I implement it on live website

I am using react + nodemailer to make a contact form for my portfolio website, however I'm having some issues.
First issue is that the email does get sent, but as soon as it sends it opens a new window with the message as part of the url, which is not supposed to happen.
Before submitting info for email
After submition of info
Second, I want to use it in a live website instead in only my localhost:3000 -> https://example.com, but I havent found anything in the docs of nodemailer.
Here is the code of the server and the react code:
import React from 'react';
import { useState } from 'react';
import './contactForm.css';
import { Footer } from '../../containers';
import axios from 'axios';
const ContactForm = () => {
//const [status, setStatus] = useState("Submit");
const [recipient_email, setEmail] = useState("");
const [name, setName] = useState("");
const [message, setMessage] = useState("");
function sendMail(){
if(recipient_email && name && message){
axios
.post('http://localhost:5000/send_email', {
recipient_email,
name,
message,
})
.then(() => alert('Message sent succesfuly'))
.catch(() => alert('Oops something went wrong'));
return;
}
return alert('Fill in all the fields to continue');
};
return (
<div className='RO__ContactForm' id='contactForm'>
<div className='RO__ContactForm-title'>
<h3>Contact</h3>
<h1>I'm here to help you level up</h1>
</div>
<div className='RO__ContactForm-content'>
<div className='RO__ContactForm-content_description'>
<p>I'm just on click away to help you take your company
to the next level. Fill in the form to share more
details about the project or your favorite movie.
Either way, I'd love to talk.</p>
<p></p>
</div>
<form
className='RO__ContactForm-content_form'
target='_blank'
>
<div className='RO__ContactForm-content_form_name'>
<div className='RO__ContactForm-content_form_nameTitle'>
<h5>What's your name?</h5>
</div>
<input
className='RO_ContactForm-content_form_nameInput'
type= 'text'
id='name'
onChange={ (e) => setName(e.target.value) }
name='name' required
/>
</div>
<div className='RO__ContactForm-content_form_email'>
<div className='RO__ContactForm-content_form_emailTitle'>
<h5>Your email</h5>
</div>
<input
className='RO__ContactForm-content_form_emailInput'
type='email'
id='email'
onChange={ (e) => setEmail(e.target.value) }
name='email' required
/>
</div>
<div className='RO__ContactForm-content_form_info'>
<div className='RO__ContactForm-content_form_infoTitle'>
<h5>What can I help you with?</h5>
</div>
<textarea
className='RO__ContactForm-content_form_infoContent'
id='message'
onChange={ (e) => setMessage(e.target.value) }
name='message' required
/>
</div>
<div className='RO__ContactForm-content_form_button'>
<button
onClick = {() => sendMail()}
type='submit'
>
Submit
</button>
</div>
</form>
</div>
<div className='RO__ContactForm-footer'>
<Footer />
</div>
</div>
)
}
export default ContactForm
server code:
const { response } = require('express');
const express = require('express');
const nodemailer = require('nodemailer');
const cors = require('cors');
const app = express();
const port = 5000;
app.use(cors());
app.use(express.json({ limit: '25mb' }));
app.use(express.urlencoded({ limit: '25mb' }));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
});
function sendEmail({ recipient_email, name, message }){
return new Promise((resolve, reject) => {
var transporter = nodemailer.createTransport({
service: 'Hotmail',
auth: {
user: '***********#hotmail.com',
pass: '**********',
},
});
const mail_configs = {
from: 'darkknight-3096#hotmail.com',
to: 'irvin.rafael.3096#gmail.com',
subject: 'Test',
text: `Name: ${name} \n Email: ${recipient_email} \n Message: ${message}`,
};
transporter.sendMail(mail_configs, function(error, info){
if(error){
console.log(error);
return reject({ message: 'An error has occured' });
}
return resolve({ message: 'Email has been sent succesfuly' });
});
});
}
app.get('/contactForm', (req, res) => {
sendEmail()
.then((response) => res.send(response.message), console.log(response.message))
.catch((error) => res.status(500).send(error.message));
});
app.post("/send_email", (req, res) => {
sendEmail(req.body)
.then((response) => res.send(response.message))
.catch((error) => res.status(500).send(error.message));
});
app.listen(port, () => {
console.log(`nodemailerProject is listening at localhost:${port}`);
});

react/datastax/firebase app, submit button works only on local machine but not working on iphone or other macbooks

I have a react app that sends input data to astradb and hosted on firebase domains, i'm using a rest api, the post method works on localhost:3000 and the firebase domain on my computer/network but when i try to submit my form on an iphone or another macbook, the submit button does not work
Ive tried to see it there are any permission problems with datastax/astradb or firebase and i cannot seem to find a good answer.
Ive tried on android phones also, still no response from the submit button
Since i cannot inspect the page on a phone with chrome, i really cant see the errors coming back on the console or network, can anyone please help me
This is my ContactForm.js
import { Checkbox, useCheckboxState } from "pretty-checkbox-react"
import React, { useRef, useState } from "react"
import { useNavigate } from 'react-router-dom'
import axios from 'axios'
import emailjs from "#emailjs/browser"
const ContactForm = () => {
const navigate = useNavigate()
const [permission, setPermission] = useState(null)
// const form = useRef()
const [formData, setFormData] = useState({
datetime: new Date().toISOString(),
fName: "",
lName: "",
email: "",
zipCode: "",
phoneNumber: "",
services: [],
})
const serviceData = [
"Business Development",
"Brand Creation",
"Logo Design",
"Digital Marketing/Ads",
"Video/Photography",
"Social Media/Content",
"Web Development",
]
const handleSubmit = async (e) => {
//dont refresh
e.preventDefault()
//atra db
const response = await axios.post("http://localhost:8000/customers", {
formData,
})
const success = response.status === 200
if (success) {
console.log("post was successful")
navigate("/exitpage")
}
//clear fromData
setFormData({
datetime: "",
fName: "",
lName: "",
email: "",
zipCode: "",
PhoneNumber: "",
services: [],
})
//clear checkboxes
setPermission(false)
}
const handleChange = (e) => {
const value = e.target.value
const name = e.target.name
setFormData((prevState) => ({
...prevState,
[name]: value,
}))
}
console.log(formData)
return (
<div className="contact-form">
<div className="container">
<div className="row">
<form validate autocomplete="on" onSubmit={handleSubmit}>
<div className="col">
<input
type="text"
value={formData.fName}
placeholder="first name"
name="fName"
onChange={handleChange}
required={true}
/>
<input
type="text"
value={formData.lName}
placeholder="last name"
name="lName"
onChange={handleChange}
required={true}
/>
</div>
<div className="col">
<input
type="email"
value={formData.email}
placeholder="example#email.com"
name="email"
onChange={handleChange}
required={true}
/>
</div>
<div className="col">
<input
type="number"
value={formData.zipCode}
placeholder="e.g. 66801"
name="zipCode"
onChange={handleChange}
required={true}
/>
</div>
<div className="col">
<input
type="tel"
value={formData.phoneNumber}
placeholder="e.g. 6203341100"
name="phoneNumber"
onChange={handleChange}
required={true}
/>
</div>
<fieldset>
<legend>
<h1>Please Select Services:</h1>
</legend>
{serviceData.map((data) => (
<div className="col">
<label>
<Checkbox
style={{}}
color="success"
className="service"
animation="rotate"
checked={permission}
plain
icon={<i className="mdi mdi-close" />}
value={data}
name="services"
onChange={(e) => {
if (!formData.services.includes(e.target.value)) {
setFormData({
...formData,
services: formData.services.concat(e.target.value),
})
} else {
setFormData({
...formData,
services: formData.services.filter(
(item) => item != e.target.value
),
})
}
}}
>
{data}
</Checkbox>
</label>
</div>
))}
</fieldset>
<button
type="submit"
className="col submit buy-btn"
onClick={handleSubmit}
>
Submit
</button>
</form>
</div>
</div>
</div>
)
}
export default ContactForm
this is my server.js post method for the contact form
const PORT = process.env.PORT || 8000
const express = require("express")
const cors = require("cors")
require("dotenv").config()
const axios = require("axios")
const app = express()
app.use(cors())
app.use(express.json())
const url = process.env.URL
const token = process.env.ASTRA_DB_TOKEN
//create customer
app.post("/customers", async (req, res) => {
const formData = req.body.formData
const options = {
method: "POST",
headers: {
Accepts: "application/json",
"X-Cassandra-Token": token,
"Content-Type": "application/json",
},
data: formData,
}
try {
const response = await axios(url, options)
res.status(200).json(response.data)
} catch (e) {
console.error(e)
res.status(500).json({ message: e })
}
})
also using node v16.1.0

POST http://localhost:3000/api/v1/register 500 (Internal Server Error)

When Cloudinary is not included my Code runs fine on Postman. As I include Cloudinary to in register route to add photos to account, I am getting this error
userAction.jsx
export const register = (userData) => async (dispatch) => {
try {
dispatch({ type: REGISTER_USER_REQUEST });
const config = { headers: { "Content-Type": "multipart/form-data" } };
const { data } = await axios.post(`/api/v1/register`, userData, config);
dispatch({ type: REGISTER_USER_SUCCESS, payload: data.user });
} catch (error) {
dispatch({
type: REGISTER_USER_FAIL,
payload: error.response.data.message,
});
}
};
LoginSignup.jsx
import React, {Fragment,useRef,useState, useEffect} from "react";
import "./LoginSignUp.css";
import Loader from "../layout/Loader/Loader";
import { Link, useNavigate } from "react-router-dom";
import LockOpenIcon from '#mui/icons-material/LockOpen';
import EmailIcon from '#mui/icons-material/Email';
import PersonIcon from '#mui/icons-material/Person';
import img from "../../images/Profile.png";
import {useSelector, useDispatch} from "react-redux";
import {clearErrors, login , register} from "../../actions/userAction.jsx";
import {useAlert} from "react-alert";
export default function LoginSignUp(){
const dispatch = useDispatch();
const alert = useAlert();
const navigate = useNavigate();
const {error,loading,isAuthenticated} = useSelector((state)=>state.user);
const loginTab=useRef(null);
const registerTab = useRef(null);
const switcherTab = useRef(null);
const [loginEmail,setLoginEmail] = useState("");
const [loginPassword,setLoginPassword] = useState("");
const [user,setUser] = useState({
name:"",
email:"",
password:"",
});
const {name,email,password} = user;
const [avatar, setAvatar] = useState(img);
const [avatarPreview, setAvatarPreview] = useState(img);
function loginSubmit(e){
e.preventDefault();
dispatch((login(loginEmail,loginPassword)));
}
function registerSubmit(e){
e.preventDefault();
const myForm = new FormData();
myForm.set("name",name);
myForm.set("email",email);
myForm.set("password",password);
myForm.set("avatar",avatar);
dispatch(register(myForm));
}
function registerDataChange(e){
if(e.target.name==="avatar"){
const reader = new FileReader();
reader.onload = ()=>{
if(reader.readyState===2){
setAvatarPreview(reader.result);
setAvatar(reader.result);
}
};
reader.readAsDataURL(e.target.files[0]);
} else {
setUser({...user, [e.target.name]:e.target.value});
}
}
useEffect(()=>{
if(error){
alert.error(error);
dispatch(clearErrors());
}
if(isAuthenticated){
navigate(`/account`);
}
},[dispatch,error,alert,isAuthenticated,navigate]);
const switchTabs = (e, tab) => {
if (tab === "login") {
switcherTab.current.classList.add("shiftToNeutral");
switcherTab.current.classList.remove("shiftToRight");
registerTab.current.classList.remove("shiftToNeutralForm");
loginTab.current.classList.remove("shiftToLeft");
}
if (tab === "register") {
switcherTab.current.classList.add("shiftToRight");
switcherTab.current.classList.remove("shiftToNeutral");
registerTab.current.classList.add("shiftToNeutralForm");
loginTab.current.classList.add("shiftToLeft");
}
};
return(
<Fragment>
{loading ? <Loader/> : (
<Fragment>
<div className="LoginSignUpContainer">
<div className="LoginSignUpBox">
<div>
<div className="login_signUp_toggle">
<p onClick={(e)=>switchTabs(e,"login")}>Login</p>
<p onClick={(e)=>switchTabs(e,"register")}>Register</p>
</div>
<button ref={switcherTab}></button>
</div>
<form
className="signUpForm"
ref={registerTab}
encType="multipart/form-data"
onSubmit={registerSubmit}
>
<div className="signUpName">
<PersonIcon />
<input
type="text"
placeholder="Name"
required
name="name"
value={name}
onChange={registerDataChange}
/>
</div>
<div className="signUpEmail">
<EmailIcon />
<input
type="email"
placeholder="Email"
required
name="email"
value={email}
onChange={registerDataChange}
/>
</div>
<div className="signUpPassword">
<LockOpenIcon />
<input
type="password"
placeholder="Password"
required
name="password"
value={password}
onChange={registerDataChange}
/>
</div>
<div id="registerImage">
<img src={avatarPreview} alt="Avatar Preview" />
<input
type="file"
name="avatar"
accept="image/*"
onChange={registerDataChange}
/>
</div>
<input type="submit" value="Register" className="signUpBtn" />
</form>
</div>
</div>
</Fragment>
)}
</Fragment>
);
}
userController.jsx
exports.RegisterUser = catchAsyncErrors( async (req,res,next)=>{
// const myCloud = await cloudinary.v2.uploader.upload(req.body.avatar,{
// folder: "avatars",
// width: 150,
// crop:"scale",
// });
const {name,email,password} = req.body;
const user = await User.create({
name,
email,
password,
avatar: {
public_id:"myCloud.public_id",
url: "myCloud.secure_url",
}
});
sendToken(user,201,res);
});
I have an id on Cloudinary and imported its Name, API_KEY, API_SECRET
Backend code works well on postman without Cloudinary
In Postman you are not adding image. But in client side login form, you are adding image alongside other data.
In backend you are getting email, name, password from req.body.But image data will be available in req.file.
As an example
if (req.file) {
const avatar= req.file.originalName;
req.body = { ...req.body, avatar};
}
await Model.create(req.body);

Having trouble in showing alert box for wrong credentials in react?

I want to show an alert box if username and password is not matching. I am sending a post request from react(using axios)to nodeJS to check for email and password. Everything is working fine if credentials are correct but it is not doing anything if it is wrong(that's understandable) but I want to show an alert when it is not correct. Why is my code not working and what would be the correct way to do it?
This is react code below:
import React, {useState} from 'react';
import "./LogIn.css";
import MailIcon from '#material-ui/icons/Mail';
import LockIcon from '#material-ui/icons/Lock';
import axios from "../axios.js";
import {useNavigate} from "react-router-dom";
function SignUp() {
// States for registration
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState(false);
let navigate = useNavigate();
// Handling the email change
const handleEmail = (e) => {
setEmail(e.target.value);
};
// Handling the password change
const handlePassword = (e) => {
setPassword(e.target.value);
};
// Handling the form submission
const handleSubmit = (e) => {
e.preventDefault();
console.log(e);
if (email === '' || password === '') {
setError(true);
} else {
setError(false);
axios.post('./login',{
email,password
}).then(function (res) {
console.log(res);
if(res.request.status === 200){
navigate(`/profile/${res.data.name}`);
}else{
alert("Username/Password is incorrect.")
};
});
}
};
// // Showing error message if error is true
const errorMessage = () => {
return (
<div
className="error"
style={{
display: error ? '' : 'none',
}}>
<h4>Please enter all the fields.</h4>
</div>
);
};
return (
<div className="form">
<form>
<h1>Log In</h1>
<p>It's quick and easy.</p>
{/* Labels and inputs for form data */}
<div className="input_field">
<MailIcon className="icon" fontSize="small"/>
<input onChange={handleEmail} className="input" placeholder="Email"
value={email} type="email" />
</div>
<div className="input_field">
<LockIcon className="icon" fontSize="small"/>
<input onChange={handlePassword} className="last-input" placeholder="Password"
value={password} type="password" />
</div>
{/* Calling to the methods */}
<div className="messages">
{errorMessage()}
</div>
<br/> <br/>
<button onClick={handleSubmit} className="btn" type="submit">
Log In
</button>
</form>
</div>
);
}
export default SignUp
This is nodeJs code:
import express from "express";
import mongoose from "mongoose";
import bodyParser from "body-parser";
import Cors from "cors";
const app=express();
const port= process.env.PORT || 5000;
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.json());
app.use(Cors());
mongoose.connect('mongodb+srv://admin:admin15#cluster0.gmg3q.mongodb.net/NotScrapDB?retryWrites=true&w=majority', {useNewUrlParser: true, useUnifiedTopology: true});
const userSchema=mongoose.Schema({
name: String,
email: String,
password: String,
});
const User= mongoose.model("User", userSchema);
app.get("/", (req,res)=>{
res.send("Hello World!Welcome to NOTSCRAP backend");
});
app.get("/register", (req, res)=>{
res.send("registered");
});
app.post("/register", (req,res)=>{
const newUser = req.body;
User.create(newUser, (err, data) => {
if(err){
res.send(err)
} else{
res.send(data);
}
});
});
app.post("/login", (req, res)=>{
const user_email = req.body.email;
const user_password = req.body.password;
if(User.findOne({email: user_email}, function(err, foundUser){
if(err){
res.send(err);
} else{
if(foundUser){
if(foundUser.password === user_password){
res.send(foundUser);
}
}
}
}))
console.log(req.body);
});
app.listen(port, ()=>{
console.log(`Server is up and running on port ${port}`);
})
Issue is in handleSubmit of the react code.
you should probably keep a variable:
const [credentialError, setCredentialError] = useState('');
....
And rather than calling alert from the error setting the value for this credentialError variable.
...
console.log(res);
if(res.request.status === 200){
setCredentialError('')
navigate(`/profile/${res.data.name}`);
}else{
setCredentialError('Credential Error (Your custom message)')
};
...
Then use this variable to show a message in the interface.

POST http://localhost:3000/api/auth/register 404 (Not Found)

So I have created a backend for register auth, In the Postman works fine, I am getting user to the mondoDb as well, we but when I try to create actual Auth on the localhost:3000/front end. In the console it gives me error.
xhr.js:177 POST http://localhost:3000/api/auth/register 404 (Not Found) if someone could help me where would this kind of error appear .
controllers
exports.register = async (req, res, next) => {
const { username, email, password } = req.body;
try {
const user = await User.create({
username,
email,
password,
});
sendToken(user, 200, res);
} catch (err) {
next(err);
}
};
Routes
const express=require('express');
const router = express.Router();
const {
register,
login,
resetPassword,
forgotPassword}= require('../controllers/auth')
router.route('/register').post(register);
router.route('/login').post(login);
router.route('/forgotpassword').post(forgotPassword);
router.route("/resetpassword/:resetToken").put(resetPassword);
module.exports= router;
Register
import { useState } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
const Register = ({ history }) => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmpassword, setConfirmPassword] = useState("");
const [error, setError] = useState("");
const registerHandler = async (e) => {
e.preventDefault();
const config = {
header: {
"Content-Type": "application/json",
},
};
if (password !== confirmpassword) {
setPassword("");
setConfirmPassword("");
setTimeout(() => {
setError("");
}, 5000);
return setError("Passwords do not match");
}
try {
const { data } = await axios.post(
"/api/auth/register",
{
username,
email,
password,
},
config
);
localStorage.setItem("authToken", data.token);
history.push("/");
} catch (error) {
setError(error.response.data.error);
setTimeout(() => {
setError("");
}, 5000);
}
};
return (
<div className="register-screen">
<form onSubmit={registerHandler} className="register-screen__form">
<h3 className="register-screen__title">Register</h3>
{error && <span className="error-message">{error}</span>}
<div className="form-group">
<label htmlFor="name">Username:</label>
<input
type="text"
required
id="name"
placeholder="Enter username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="email">Email:</label>
<input
type="email"
required
id="email"
placeholder="Email address"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password:</label>
<input
type="password"
required
id="password"
autoComplete="true"
placeholder="Enter password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="confirmpassword">Confirm Password:</label>
<input
type="password"
required
id="confirmpassword"
autoComplete="true"
placeholder="Confirm password"
value={confirmpassword}
onChange={(e) => setConfirmPassword(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary">
Register
</button>
<span className="register-screen__subtext">
Already have an account? <Link to="/login">Login</Link>
</span>
</form>
</div>
);
};
export default Register;
You are having a problem with CORS. There's a package that can solve that.
npm i cors
The package can be found in: https://www.npmjs.com/package/cors
For you to use it you just need to import it and use it as follow:
var cors = require('cors');
express.use(cors());
You can also customise it more following the documentation.

Categories