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.
Related
Trying to POST request to send data to database but it always shows 400 bad request.
The AuthReducer file is as follow. Data is not getting posted when done in Frontend but its properly working when tested in postman api.
export const Register = (username, email , password) => async(disptach) => {
try{
disptach({type:REGISTER_USER_REQUEST})
const config = {
Headers:{
'Content-Type':'application/json'
}
}
const { data } = await axios.post('/EShop/register', {username ,email , password} , config)
disptach({
type:REGISTER_USER_SUCCESS,
payload:data.user
})
}catch(error){
disptach({
type:REGISTER_USER_FAIL,
payload : error.response.data.message
})
}
}
The register form is as follow..
import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom"
import { useSelector, useDispatch } from "react-redux"
import Loader from "./loader";
import { Register } from "../actions/UserAction";
import "../css-files/Account.css"
export default function register() {
const [email, setemail] = useState('');
const [password, setpassword] = useState('');
const [username, setusername] = useState('');
const disptach = useDispatch();
const navigate = useNavigate();
const { isAuthenticated, error, loading } = useSelector(state => state.user)
useEffect(() => {
if (isAuthenticated) {
navigate('/account/login')
}
}, [disptach, isAuthenticated])
const SubmitRegisterHandler = (e) => {
e.preventDefault()
disptach(Register(username, email, password))
}
return (
<div id="Account_container">
{loading ?
<Loader />
:
<div id="wrapper">
<div id="Wrap_First">
<img src="https://res.cloudinary.com/dqxozrie1/image/upload/v1659935744/eshop/online-registration-sign-up_gfb2gs.webp" />
</div>
<div id="Wrap_Second">
<div id="login">
<h2>Create New Account</h2>
<form onSubmit={SubmitRegisterHandler}>
<input
required
type="text"
placeholder="Username"
value={username}
onChange={(e) => { setusername(e.target.value) }}
/>
<input
required
type="email"
placeholder="Email"
value={email}
onChange={(e) => { setemail(e.target.value) }}
/>
<input
required
type="password"
placeholder="Password"
value={password}
onChange={(e) => { setpassword(e.target.value) }}
/>
<button>Register</button>
</form>
<p id="existing_acc"><Link to="/account/login">Already have an account !</Link></p>
</div>
</div>
</div>
}
</div>
);
}
It gives 400 bad request always. Please help me how to resolve this issue.
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"
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>
);
}
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>
);
}
So this problem I am facing for quite some time. Basically Registering user work to some extent. This is what is happening, upon the user being created and me getting the Auth token displayed in the dev-tools/Application and me being pushed to the home as I should.
When I refresh the page I get this error × Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information. I can fix this by clearing the localStorage. So if every time a new user is created, and if it wants to refresh the page, I will have to clear local storage every time. Which is totally not convenient.
There is another error, The logout handler is bugging, when I press the logout button it is displaying this error TypeError: Cannot read property 'push' of undefined and it pointing out the error is located in the UserContext. I would really appreciate some help really.
User Context
import React from "react";
import { useHistory } from "react-router-dom"
const UserContext = React.createContext();
function getUserFromLocalStorage() {
return localStorage.getItem("authToken")
? JSON.parse(localStorage.getItem("authToken"))
: { username: null, token: null };
}
function UserProvider({ children }) {
const [user, setUser] = React.useState(getUserFromLocalStorage());
const routerHistory = useHistory()
const logoutHandler = () =>{
localStorage.removeItem("authToken");
setUser(user);
routerHistory.push("/")
}
return (
<UserContext.Provider
value={{ user, setUser, logoutHandler }}
>
{children}
</UserContext.Provider>
);
}
export { UserContext, UserProvider };
Login
import React, { useState, } from "react";
import { useHistory } from "react-router-dom"
import axios from "axios";
import { Link } from "react-router-dom";
import "./Signin.css";
import { UserContext } from "../../context/user";
const Login = () => {
const { user, setUser } = React.useContext(UserContext);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const history = useHistory()
const loginHandler = async (e) => {
e.preventDefault();
const config = {
header: {
"Content-Type": "application/json",
},
};
try {
const { data } = await axios.post(
"http://localhost:5000/api/auth/login",
{ email, password },
config
);
user.authToken = data.token;
setUser(user)
history.push("/");
} catch (error) {
if (error.response) {
setError(error.response.data.error);
}
setTimeout(() => {
setError("");
}, 5000);
}
};
return (
<div className="signin">
<Link to='/'>
<img src='/audible/logo.png' />
</Link>
<form onSubmit={loginHandler} className="form__container">
<h3>Sign in with your Amazon account</h3>
{error && <span className="error__message">{error}</span>}
<span className='labels'>Email </span>
<input
className="input__field"
type="email"
required
id="email"
onChange={(e) => setEmail(e.target.value)}
value={email}
tabIndex={1}
/>
<span className='signin__forgot'>Password{" "}
<Link className='links' to="/forgotpassword" >
Forgot Password?
</Link>
</span>
<input
className="input__field"
type="password"
required
id="password"
autoComplete="true"
onChange={(e) => setPassword(e.target.value)}
value={password}
tabIndex={2}
/>
<button type="submit" className="signin__btn">
Sign In
</button>
<span className='new__sign'>New to Amazon? </span>
<Link to="/register">
<button className='signin__register'>
Create your amazon account
</button>
</Link>
</form>
</div>
);
};
export default Login;
Register
import { useState, } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import { useHistory } from "react-router-dom"
const Register = () => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmpassword, setConfirmPassword] = useState("");
const [error, setError] = useState("");
const routerHistory = useHistory()
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(
"http://localhost:5000/api/auth/register",
{
username,
email,
password,
},
config
);
localStorage.setItem("authToken", data.token);
routerHistory.push('/login')
} catch (error) {
if (error.response) {
setError(error.response.data.error);
}
setTimeout(() => {
setError("");
}, 5000);
}
};
return (
<div className="signin">
<Link to='/'>
<img src='/audible/logo.png' />
</Link>
<form onSubmit={registerHandler} className="form__container">
<h3>Create account</h3>
{error && <span className="error__message">{error}</span>}
<span className='labels'>Username</span>
<input
type="text"
className="input__field"
required
id="name"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<span className='labels'>Email</span>
<input
type="email"
className="input__field"
required
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<span className='labels'>Password</span>
<input
type="password"
required
id="password"
className="input__field"
autoComplete="true"
placeholder="At least 6 characters"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<span className='labels'>Re-enter password</span>
<input
type="password"
required
id="confirmpassword"
className="input__field"
autoComplete="true"
value={confirmpassword}
onChange={(e) => setConfirmPassword(e.target.value)}
/>
<button type="submit" className="register__btn">
Create your Amazon account
</button>
<span >
Already have an account? <Link className='links' to="/login">Login</Link>
</span>
</form>
</div>
);
};
export default Register;
Login Link
import React from "react";
import { Link, useHistory } from "react-router-dom";
import { CartContext } from "../../context/cart";
import { UserContext } from "../../context/user";
export default function LoginLink() {
const { user, logoutHandler } = React.useContext(UserContext);
const { clearCart } = React.useContext(CartContext);
if (user.authToken) {
return (
<button
onClick={() => {
logoutHandler();
clearCart()
}}
className="login-btn"
>
logout
</button>
);
}
return <Link to="/login">Signin</Link>;
}