function Login() {
const [email, setEmail] = useState("");
const [password, setpassword] = useState("");
const [users, setUser] = useState([]);
function login() {
fetch(
"http://116.202.231.219:8069/Restaurant/Login_Updated?Cont4=" +
email +
"&Pswd=" +
password
).then((result) => {
result.json().then((resp) => {
// console.warn(resp)
setUser(resp);
console.log(resp);
});
});
}
return (
<div className="col-sm-6 offset-sm-3">
<h1>Login Page</h1>
<br />
<input
type="text"
className="form-control"
onChange={(e) => setEmail(e.target.value)}
/>
<br />
<br />
<input
type="password"
className="form-control"
onChange={(e) => setpassword(e.target.value)}
/>
<br />
<br />
<button onClick={login} className="btn btn-primary">
Login
</button>
</div>
);
}
now I want to check that if the data being fetched is the same as the data being put in the inputs so I am trying using "IF" but the "RESP" variable is not global I mean that it is not working with "IF". So can you guys help me how to do a check that the Email pass is equal to the Email pass from the API.
As you can see that API is getting the cont4 and pass from the input tags and giving back the objects in return but I am not able to run the success check on this API that if it returns object go to dashboard else throw alert of error
import axios from 'axios';
//add axios in your project
function Login() {
const [email, setEmail] = useState("");
const [password, setpassword] = useState("");
const [users, setUser] = useState({});
loginHandel = () => {
const url = `http://116.202.231.219:8069/Restaurant/Login_Updated?Cont4=${email}&Pswd=${password}`
axios.get(url).then((res) => {
//check the res if its getting the correct data or not?
//restructure accordingly
console.log(res);
const persons = res;
if ((persons?.email === email) && (persons?.password === password)) {
//perform any thing here
setUser(persons);
} else {
console.log("User email and passwoed mismatched!")
}
}).catch(err => {
//handel your error
console.log(err);
})
}
return (
<div className="col-sm-6 offset-sm-3">
<h1>Login Page</h1>
<br />
<form>
</form>
<input
type="text"
className="form-control"
onChange={(e) => setEmail(e.target.value)}
/>
<br />
<br />
<input
type="password"
className="form-control"
onChange={(e) => setpassword(e.target.value)}
/>
<br />
<br />
<button onClick={loginHandel} className="btn btn-primary">
Login
</button>
</div>
);
}
Related
I try to learn react component rendering but the problem is that I have a login page with 2 input field and 1 button as:
function LoginPage() {
const [username, changeUsername] = useState('');
const [password, changePassword] = useState('');
const loginRequest = async (username, password) => {
let response = await service.loginRequest(username, password);
console.log(response);
}
return (
<Card hoverable className='transaction-button-card'>
<h1>Enter username and password</h1>
<input type="text"
placeholder="Username"
onChange={e => changeUsername(e.target.value)}
value={username}></input>
<input type="text"
placeholder="Password"
onChange={e => changePassword(e.target.value)}
value={password}></input>
<Button onClick={loginRequest(username, password)}
className='withdraw-deposit-button'>Login/Deposit</Button>
</Card>
);
}
export default LoginPage;
When the page is rendered the function loginRequest(username, password) automatically triggered once and for every input characters to input fields are also triggering the same function and sending request for each input char. How can I solve this problem? (I don't want to send request automatically when the page is opened and send request with only with button). I would appreciate if you define the problem.
`
function LoginPage() {
const [username, changeUsername] = useState('');
const [password, changePassword] = useState('');
const loginRequest = async (username, password) => {
let response = await service.loginRequest(username, password);
console.log(response);
}
return (
<Card hoverable className='transaction-button-card'>
<h1>Enter username and password</h1>
<input type="text"
placeholder="Username"
onChange={e => changeUsername(e.target.value)}
value={username}></input>
<input type="text"
placeholder="Password"
onChange={e => changePassword(e.target.value)}
value={password}></input>
<Button onClick={() => loginRequest(username, password)}
className='withdraw-deposit-button'>Login/Deposit</Button>
</Card>
);
}
export default LoginPage;
`
Good afternoon everyone. I have 2 pages: one responsible for displaying List of Users in the table (data comes from fetching), then on Add User button click opens a Modal window with Sign Up form. On submitting this form, data about a new user is sent to an api (fetch POST), then sign up form closes and then the List of Users table is supposed to be updated with a newly added user. I fail to figure out how to correctly perform this update. Simple getUser() call in handleUserFormSubmit function doesn't do the trick (table is not re-rendered). Thanks in advance for any help
// Sign-Up Form Component
import React, { useState, useEffect } from "react";
const SignUpForm = ({
isFormVisible,
setIsFormVisible,
userList,
getUsers,
}) => {
const [usernameList, setUsernameList] = useState([]);
const [username, setUsername] = useState("");
const [usertype, setUsertype] = useState("");
const [password, setPassword] = useState("");
const [verifyPassword, setVerifyPassword] = useState("");
const [isChecked, setIsChecked] = useState(true);
const getUsernameList = () =>
userList.forEach(({ username }) => usernameList.push(username));
useEffect(() => {
getUsernameList();
console.log(usernameList);
}, []);
const addNewUser = async () => {
try {
const response = await fetch(
"http://www.someapi.com/add",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
username,
usertype,
password,
}),
}
);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error.message);
}
};
const handleUserFormSubmit = (e) => {
e.preventDefault();
addNewUser();
setIsFormVisible(false);
getUsers();
}
};
return (
<>
{isFormVisible && (
<div
className={`${
isFormVisible ? "modal-overlay show-modal" : "modal-overlay"
}`}
>
<div className="sign-up-container">
<div className="sign-up-header-container">
<h2>Sign Up</h2>
<p>Please fill in this form to create an acoount</p>
</div>
<form className="form" onSubmit={(e) => e.preventDefault()}>
<label htmlFor="username">Username</label>{" "}
<br />
<input
type="text"
placeholder="Enter username"
id="username"
name="username"
value={username}
required
onChange={(e) => {
setUsername(e.target.value.toLowerCase());
setIsNameProvided(true);
}}
/>
<br />
<label htmlFor="usertype">User type</label>{" "}
<br />
<select
name="usertype"
id="usertype-select"
required
onChange={(e) => {
setUsertype(e.target.value);
setIsTypeSelected(true);
}}
>
<option value=""></option>
<option value="instructor">instructor</option>
<option value="maintenance">maintenance</option>
</select>
<br />
<label htmlFor="password">Password</label>{" "}
<br />
<input
type="password"
placeholder="Enter password"
id="password"
name="password"
required
value={password}
onCopy={(e) => e.preventDefault()}
onPaste={(e) => e.preventDefault()}
onChange={(e) => {
setPassword(e.target.value);
setIsPasswordProvided(true);
}}
/>
<br />
<label htmlFor="rpassword">Repeat Password</label>{" "}
<br />
<input
type="password"
placeholder="Repeat"
id="rpassword"
name="rpassword"
required
value={verifyPassword}
onCopy={(e) => e.preventDefault()}
onPaste={(e) => e.preventDefault()}
onChange={(e) => {
setVerifyPassword(e.target.value);
setIsConfirmPasswordProvided(true);
}}
/>{" "}
<br />
<input
type="checkbox"
id="remember"
name="remember"
checked={isChecked}
onChange={() => setIsChecked(!isChecked)}
/>
<label htmlFor="remember">Remember me</label>
<p className="terms-privacy">
By creating an account you agree to our{" "}
Terms & Privacy
</p>
<div className="btn-container">
<button
type="button"
className="cancel-btn"
onClick={() => setIsFormVisible(false)}
>
CANCEL
</button>
<button
type="submit"
className="sign-up-btn"
onClick={(e) => handleUserFormSubmit(e)}
>
SIGN UP
</button>
</div>
</form>
</div>
</div>
)}
</>
);
};
export default SignUpForm;
// List Of Users Component:
import React, { useState, useEffect } from "react";
import Loading from "./Loading";
import SignUpForm from "./SignUpForm";
import "./User.css";
const User = () => {
const [userList, setUserList] = useState([]);
const [loading, setLoading] = useState(true);
const [isFormVisible, setIsFormVisible] = useState(false);
const getUsers = async () => {
setLoading(true);
try {
const response = await fetch(
"http://www.someapi.com"
);
const data = await response.json();
setUserList(data);
setLoading(false);
} catch (error) {
console.error(error.message);
setLoading(false);
}
};
useEffect(() => {
getUsers();
}, []);
if (loading) return <Loading />;
return (
<section className="section-user">
<h1>List of Users</h1>
<div className="users-table-container">
<table className="users-table">
<thead>
<tr>
<th>Username</th>
<th>User type</th>
</tr>
</thead>
<tbody>
{userList.map(({ username, userType, hashedPswd }) => (
<tr key={hashedPswd}>
<td>{username}</td>
<td>{userType}</td>
</tr>
))}
</tbody>
</table>
</div>
<button className="add-user-btn" onClick={() => setIsFormVisible(true)}>
Add User
</button>
{isFormVisible && (
<SignUpForm
isFormVisible={isFormVisible}
setIsFormVisible={setIsFormVisible}
userList={userList}
getUsers={getUsers}
/>
)}
</section>
);
};
export default User;
You are directly manipulating a state rather than using setState. In this case react does not re-render the page even if you manipulate the state. So:
// wrong
const getUsernameList = () =>
userList.forEach(({ username }) => usernameList.push(username));
// correct
const getUsernameList = () => {
const list = userList.map(user => user.username)
setUsernameList(list)
}
*Edit: I think you are not saving your response data after creating a new user
In User component add
useEffect(() => {
if (isFormVisible) getUsers();
}, [isFormVisible]);
I am trying to upload a photo to mySQL database using a node backend but for some reason I am getting that what I have uploaded is undefined.
I have declared a new variable "Photo2" which is storing that photo and I console.log it but I get "undefined" in my console
The form:
import axios from "axios";
import { React, useState, useEffect } from "react";
import { useHistory, withRouter } from "react-router-dom";
function UserMaster_Edit(props) {
const [CmpnyCode, setCmpnyCode] = useState("");
const [UserID, setUserID] = useState("");
const [UserFullName, setUserFullName] = useState("");
const [UserDetail, setUserDetail] = useState("");
const [LoginID, setLoginID] = useState("");
const [Password, setPassword] = useState("");
const [UserPin, setUserPin] = useState("");
const [UserEmailID, setUserEmailID] = useState("");
const [UserFP, setUserFP] = useState("");
const [Photo, setPhoto] = useState("");
const [IsActive, setIsActive] = useState("");
const [LicCount, setLicCount] = useState("");
const [DateCreated, setDateCreated] = useState("");
const [CreatedBy, setCreatedBy] = useState("");
const [RecordChanged, setRecordChanged] = useState("");
const [LocationID, setLocationID] = useState("");
const [isValid, setisValid] = useState("");
const [isDeleted, setisDeleted] = useState("");
const history = useHistory();
const argu = props.match.params.UserID;
useEffect(() => {
axios.get("http://localhost:8000/getuserid/" + argu).then((response) => {
setCmpnyCode(response.data[0].CmpnyCode);
setUserID(response.data[0].UserID);
setUserFullName(response.data[0].UserFullName);
setUserDetail(response.data[0].UserDetail);
setLoginID(response.data[0].LoginID);
setPassword(response.data[0].Password);
setUserPin(response.data[0].UserPin);
setUserEmailID(response.data[0].UserEmailID);
setUserFP(response.data[0].UserFP);
setPhoto(response.data[0].Photo);
setIsActive(response.data[0].IsActive.data[0]);
setLicCount(response.data[0].LicCount);
setDateCreated(response.data[0].DateCreated);
setCreatedBy(response.data[0].CreatedBy);
setRecordChanged(response.data[0].RecordChanged.data[0]);
setLocationID(response.data[0].LocationID);
setisValid(response.data[0].isValid);
setisDeleted(response.data[0].isDeleted);
});
}, [argu]);
const editData = () => {
axios.put("http://localhost:8000/upusermst/" + argu, {
CmpnyCode,
UserID,
UserFullName,
UserDetail,
LoginID,
Password,
UserPin,
UserEmailID,
UserFP,
Photo,
IsActive,
LicCount,
DateCreated,
CreatedBy,
RecordChanged,
LocationID,
isValid,
isDeleted,
});
history.push("/usermst");
};
return (
<div className="App">
<div className="auth-wrapper">
<div className="auth-inner">
<form enctype="multipart/form-data" onSubmit={() => editData()}>
<h3> Edit User Master</h3>
<div>
<div className="form-class8">
<div className="form-group">
<label>Company Code</label>
<input
type="text"
className="form-control"
placeholder="CompanyCode"
value={CmpnyCode}
onChange={(e) => {
setCmpnyCode(e.target.value);
}}
name="CmpnyCode"
/>
</div>
<div className="form-group">
<label>UserID</label>
<input
type="text"
className="form-control"
placeholder="UserID"
value={UserID}
onChange={(e) => {
setUserID(e.target.value);
}}
name="UserID"
/>
</div>
<div className="form-group">
<label>UserFullName</label>
<input
type="text"
className="form-control"
placeholder="UserFullName"
value={UserFullName}
onChange={(e) => {
setUserFullName(e.target.value);
}}
name="UserFullName"
/>
</div>
<div className="form-group">
<label>UserDetail</label>
<input
type="text"
className="form-control"
placeholder="UserDetail"
onChange={(e) => {
setUserDetail(e.target.value);
}}
name="UserDetail"
value={UserDetail}
/>
</div>
<div className="form-group">
<label>LoginID</label>
<input
type="text"
className="form-control"
placeholder="LoginID"
onChange={(e) => {
setLoginID(e.target.value);
}}
name="LoginID"
value={LoginID}
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="text"
className="form-control"
placeholder="Password"
onChange={(e) => {
setPassword(e.target.value);
}}
name="Password"
value={Password}
/>
</div>
<div className="form-group">
<label>UserPin</label>
<input
type="text"
className="form-control"
placeholder="UserPin"
onChange={(e) => {
setUserPin(e.target.value);
}}
name="UserPin"
value={UserPin}
/>
</div>
<div className="form-group">
<label>UserEmailID</label>
<input
type="email"
className="form-control"
placeholder="UserEmailID"
onChange={(e) => {
setUserEmailID(e.target.value);
}}
name="UserEmailID"
value={UserEmailID}
/>
</div>
</div>
<div className="form-class8">
<div className="form-group">
<label>UserFP</label>
<input
type="file"
className="form-control"
placeholder="UserFP"
onChange={(e) => {
setUserFP(e.target.value);
}}
name="UserFP"
value={UserFP}
/>
</div>
<div className="form-group">
<label>Photo</label>
<input
type="file"
className="form-control"
placeholder="Photo"
onChange={(e) => {
setPhoto(e.target.value);
}}
name="Photo"
value={Photo}
/>
</div>
<div className="form-group">
<label>IsActive</label>
<input
type="text"
className="form-control"
placeholder="IsActive"
onChange={(e) => {
setIsActive(e.target.value);
}}
name="IsActive"
value={IsActive}
/>
</div>
<div className="form-group">
<label>LicCount</label>
<input
type="text"
className="form-control"
placeholder="LicCount"
onChange={(e) => {
setLicCount(e.target.value);
}}
name="LicCount"
value={LicCount}
/>
</div>
<div className="form-group">
<label>DateCreated</label>
<input
type="text"
className="form-control"
placeholder="DateCreated"
onChange={(e) => {
setDateCreated(e.target.value);
}}
name="DateCreated"
value={DateCreated}
/>
</div>
<div className="form-group">
<label>CreatedBy</label>
<input
type="text"
className="form-control"
placeholder="CreatedBy"
onChange={(e) => {
setCreatedBy(e.target.value);
}}
name="CreatedBy"
value={CreatedBy}
/>
</div>
<div className="form-group">
<label>RecordChanged</label>
<input
type="text"
className="form-control"
placeholder="RecordChanged"
onChange={(e) => {
setRecordChanged(e.target.value);
}}
name="RecordChanged"
value={RecordChanged}
/>
</div>
<div className="form-group">
<label>LocationID</label>
<input
type="text"
className="form-control"
placeholder="LocationID"
onChange={(e) => {
setLocationID(e.target.value);
}}
name="LocationID"
value={LocationID}
/>
</div>
</div>
<div className="form-class8">
<div className="form-group">
<label>isValid</label>
<input
type="date"
className="form-control"
placeholder="isValid"
onChange={(e) => {
setisValid(e.target.value);
}}
name="isValid"
value={isValid}
/>
</div>
<div className="form-group">
<label>isDeleted</label>
<input
type="date"
className="form-control"
placeholder="isDeleted"
onChange={(e) => {
setisDeleted(e.target.value);
}}
name="isDeleted"
value={isDeleted}
/>
</div>
</div>
<button className="btn btn-primary btn-block">Edit</button>
</div>
</form>
</div>
</div>
</div>
);
}
export default withRouter(UserMaster_Edit);
The fields that you are looking for are UserFP and Photo which are of type file.
Node backend:
const multer = require("multer");
const upload = multer({ storage: multer.memoryStorage() });
app.put("/upusermst/:UserID", upload.single("Photo"), (req, res) => {
const userid = req.params.UserID;
const CompanyCode = req.body.CmpnyCode;
const UserID = req.body.UserID;
const UserFullName = req.body.UserFullName;
const UserDetail = req.body.UserDetail;
const LoginID = req.body.LoginID;
const Password = req.body.Password;
const UserPin = req.body.UserPin;
const UserEmailID = req.body.UserEmailID;
const UserFP = req.body.UserFP;
const Photo = req.body.Photo;
const Photo2 = req.file;
const IsActive = req.body.IsActive;
const LicCount = req.body.LicCount;
const DateCreated = req.body.DateCreated;
const CreatedBy = req.body.CreatedBy;
const RecordChanged = req.body.RecordChanged;
const LocationID = req.body.LocationID;
const isValid = req.body.isValid;
const isDeleted = req.body.isDeleted;
console.log(Photo2);
db.query(
"UPDATE usermst SET CmpnyCode=?,UserID=?,UserFullName=?,UserDetail=?,LoginID=?,Password=?,UserPin=?,UserEmailID=?,UserFP=?,Photo=?,IsActive=?,LicCount=?,DateCreated=?,CreatedBy=?,RecordChanged=?,LocationID=?,isValid=?,isDeleted=? WHERE UserID=?",
[
CompanyCode,
UserID,
UserFullName,
UserDetail,
LoginID,
Password,
UserPin,
UserEmailID,
UserFP,
Photo,
IsActive,
LicCount,
DateCreated,
CreatedBy,
RecordChanged,
LocationID,
isValid,
isDeleted,
userid,
],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
}
);
});
Note that there is variable named Photo already but that was what I did before, now I am doing req.file for Photo2 and that is resulting to undefined.
I would really appreciate if someone can edit the code for me for better understanding with some explanation as to why I may be getting undefined for "Photo2"
After a lot of digging I finally figured out the problem.
I had not installed jQuery hence the put request being sent by axios was giving the result undefined in the backend. I used fetch instead and it worked.
The code is now as follows:
The form:
const uploadPhoto = (event, argu) => {
event.preventDefault();
const formData = new FormData();
formData.append("avatar", Photo);
fetch("http://localhost:8000/uploadphoto/" + argu, {
method: "PUT",
body: formData,
});
};
<form enctype="multipart/form-data">
<div className="form-group">
<label>Photo</label>
<input
type="file"
className="form-control"
placeholder="Photo"
onChange={(e) => {
setPhoto(e.target.files[0]);
}}
id="Photo"
name="Photo"
/>
</form>
Backend:
const multer = require("multer");
const fs = require("fs");
const upload = multer({ dest: "uploads/" });
app.put("/uploadphoto/:UserId", upload.single("avatar"), (req, res) => {
const userid = req.params.userId;
const photo = req.file;
const fileType = photo.mimetype.split("/")[1];
let newFileName = photo.filename + "." + fileType;
fs.rename(
`./uploads/${photo.filename}`,
`./uploads/${newFileName}`,
function () {
console.log("file renamed and uploaded");
}
);
console.log(photo);
console.log("fileName ", newFileName);
db.query(
"UPDATE usermst SET Photo=? WHERE UserID=?",
[newFileName, userid],
(err, result) => {
console.log(err);
res.json({ result });
}
);
});```
Because file type inputs are not in e.target.value. The are in e.target.files. As you have only one image that would be e.target.files[0] in your case.
<input
type="file"
lassName="form-control"
placeholder="Photo"
onChange={(e) => {
setPhoto(e.target.files[0]);
}}
name="Photo"
/>
By the way, you can't just send file along with request. You need to use formData instead.
Check out my minimal example:
import { useState } from "react";
export default function PrivatePage(props) {
const [image, setImage] = useState(null);
const [createObjectURL, setCreateObjectURL] = useState(null);
const uploadToClient = (event) => {
if (event.target.files && event.target.files[0]) {
const i = event.target.files[0];
setImage(i);
setCreateObjectURL(URL.createObjectURL(i));
}
};
const uploadToServer = async (event) => {
const body = new FormData();
body.append("file", image);
const response = await fetch("/api/formidable", {
method: "POST",
body
});
};
return (
<div>
<div>
{createObjectURL&&<img height="500px" width="1000px" src={createObjectURL}/>}
<h4>Select Image</h4>
<input type="file" name="myImage" onChange={uploadToClient} />
<button
className="btn btn-primary"
type="submit"
onClick={uploadToServer}
>
Send to server
</button>
</div>
</div>
);
}
I am fetching data from api and then store some detail in redux store and from redux store I am setting some values on browser localstorage.
I am using browser localstorage for conditional statement but because of undefined in or initial state inside the redux store my condtions are not executing.
My code:
const Login = () => {
const dispatch = useDispatch();
const { isAuth } = useSelector((state) => state.login);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const submitLoginForm = async (e) => {
e.preventDefault();
dispatch(loginPending());
const response = await fetch("https://localhost:44316/api/auth/login", {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
credentials: 'include',
body: JSON.stringify({
email,
password,
})
});
if(response.status === 200){
dispatch(loginSuccess());
debugger;
localStorage.setItem('auth',isAuth);
console.log(isAuth);
console.log(localStorage.getItem('auth'));
}
else{
dispatch(loginFailed());
}
};
if(JSON.parse(localStorage.getItem('auth')) === true){
return <Redirect to="/" />
}
return (
<React.Fragment>
<Navbar />
<div className="formContainer">
<h1>Login</h1>
<form className="loginForm" onSubmit={submitLoginForm}>
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">
Email address
</label>
<input
type="email"
className="form-control"
aria-describedby="emailHelp"
onChange={(e) => setEmail(e.target.value)}
/>
<div id="emailHelp" className="form-text">
We'll never share your email with anyone else.
</div>
</div>
<div className="mb-3">
<label htmlFor="exampleInputPassword1" className="form-label">
Password
</label>
<input
type="password"
className="form-control"
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary">
Login
</button>
</form>
</div>
</React.Fragment>
);
};
My slice Contain:
loginSuccess: (state) => {
state.isLoading = false;
state.isAuth = true;
state.error = "";
}
I want to get isAuth value from redux store and then store it inside the browser local storage. But I am getting false value in my console
In the browser redux dev tool its showing the state change.
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.