I'm working on a project using react.js in the frontend and node.js in the backend. I keep getting a POST Status Code: 404 Not Found error in my code for my signup page. Specifically, I'm getting: Cannot POST /api/users/signup. I've gone over my code a number of times, and I can't figure out what could be causing this error. I would really appreciate any help or advice on why this could be occurring. Thank you!
Frontend:
SignInScreen:
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {signup} from "../actions/userActions";
import { useNavigate } from 'react-router-dom'
export default function SignupScreen(props) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
console.log(email, password, confirmPassword)
const userSignUp = useSelector((state) => state.userSignUp);
const { userInfo, loading, error } = userSignUp;
let navigate = useNavigate()
const dispatch = useDispatch();
const submitHandler = (e) => {
e.preventDefault();
if (password !== confirmPassword) {
alert('Password and confirm password do not match');
} else {
dispatch(signup( email, password));
navigate ('/onboarding')
}
}
return (
<div className="auth">
<h2>CREATE ACCOUNT</h2>
<form onSubmit={submitHandler}>
<input
type="email"
id="email"
name="email"
placeholder="email"
required={true}
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="password"
id="password"
name="password"
placeholder="password"
required={true}
onChange={(e) => setPassword(e.target.value)}
/>
<input
type="password"
id="password-check"
name="password-check"
placeholder="confirm password"
required={true}
onChange={(e) => setConfirmPassword(e.target.value)}
/>
<input className="secondary-button" type="submit"/>
</form>
</div>
);
}
userActions.js
import Axios from 'axios';
import {
USER_SIGNUP_FAIL,
USER_SIGNUP_REQUEST,
USER_SIGNUP_SUCCESS,
} from '../constants/userConstants';
export const signup = (email, password) => async (dispatch) => {
dispatch({ type: USER_SIGNUP_REQUEST, payload: { email, password } });
try {
const { data } = await Axios.post('/api/users/signup', {
email,
password,
});
dispatch({ type: USER_SIGNUP_SUCCESS, payload: data });
dispatch({ type: USER_LOGIN_SUCCESS, payload: data });
localStorage.setItem('userInfo', JSON.stringify(data));
} catch (error) {
dispatch({
type: USER_SIGNUP_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
}
};
backend:
server.js
import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import {v4} from 'uuid';
import bcrypt from 'bcrypt';
import userRouter from './routers/userRouter.js';
dotenv.config();
const app = express()
app.use(cors())
app.use(express.json())
mongoose.connect(process.env.MONGODB_URL || 'mongodb://localhost/TC', {
useNewUrlParser: true,
useUnifiedTopology: true,
/*useCreateIndex: true,*/
});
app.use('/api/users', userRouter);
app.get('/', (req, res) => {
res.send('Server is ready');
})
app.use((err, req, res, next) => {
res.status(500).send({ message: err.message });
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Serve at http://localhost:${port}`);
});
userRouter.js
import express from 'express';
import expressAsyncHandler from 'express-async-handler';
import bcrypt from 'bcrypt';
import User from '../models/userModel.js';
import { generateToken, isAdmin, isAuth } from '../utils.js';
const userRouter = express.Router();
userRouter.post(
'/signup',
expressAsyncHandler(async (req, res) => {
const user = new User({
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8),
});
const createdUser = await user.save();
res.send({
_id: createdUser._id,
email: createdUser.email,
isAdmin: createdUser.isAdmin,
token: generateToken(createdUser),
});
}),
);
export default userRouter;
I think that you are missing the localhost in your axios call:
instead of:
const { data } = await Axios.post('/api/users/signup', {
...
try:
const { data } = await Axios.post('http://localhost:5000/api/users/signup', {
Related
I have made sure the backend works pretty fine with postman but when I try running the code on the client side, it fails with response: Failed to load resource: the server responded with a status of 400 (Bad Request)
Below are the codes controlling the functionality of the user signup and verification
/backend/routes/userRoutes.js
userRouter.post(
'/signup',
expressAsyncHandler(async (req, res) => {
try {
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: bcrypt.hashSync(req.body.password),
});
const user = await newUser.save();
const verifyToken = await new VerificationToken({
userId: user._id,
token: crypto.randomBytes(32).toString('hex'),
}).save();
const url = `${process.env.BASE_URL}/${verifyToken._id}/verify/${verifyToken.token}`;
await mailTransport(user.email, 'Verify Email', url);
res.status(201).send({
message:
'A verification link has been sent to your account, please verify ',
});
} catch (error) {
res.status(500).send({ message: 'Internal Server Error' });
}
})
);
userRouter.get('/:id/verify/:token', async (req, res) => {
try {
const user = await User.findOne({ _id: req.params.id });
if (!user) return res.status(400).send({ message: 'Invalid Link' });
const verificationToken = await VerificationToken.findOne({
userId: user._id,
token: req.params.token,
});
if (!verificationToken)
return res.status(400).send({ message: 'Invalid link' });
await User.updateOne({ verified: true });
res.status(200).send({
_id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
verified: user.verified,
token: generateToken(user),
message: 'Email verified successfully',
});
await verificationToken.remove();
// res.status(200).send({ message: 'Email verified successfully' });
} catch (error) {
res.status(500).send({ message: 'Internal Server Error' });
console.log(error);
}
});
/frontend/src/screens/SignupScreen.js
import React, { useContext, useState, useEffect } from 'react';
import Container from 'react-bootstrap/Container';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import { Helmet } from 'react-helmet-async';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import axios from 'axios';
import { Store } from '../Store';
import { toast } from 'react-toastify';
import { getError} from '../utils';
export default function SignupScreen() {
const navigate = useNavigate();
const { search } = useLocation();
const redirectInUrl = new URLSearchParams(search).get('redirect');
const redirect = redirectInUrl ? redirectInUrl : '/signup';
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [error, setError] = useState('');
const [msg, setMsg] = useState('');
const { state } = useContext(Store);
const { userInfo } = state;
const submitHandler = async (e) => {
e.preventDefault();
if (password !== confirmPassword) {
toast.error('Passwords do not match');
return;
}
try {
const { data } = await axios.post(`/api/users/signup`, {
name,
email,
password,
confirmPassword,
});
setMsg(data.message);
setError(data.error);
} catch (err) {
toast.error(getError(err));
}
};
useEffect(() => {
if (userInfo) {
navigate(redirect);
}
}, [navigate, redirect, userInfo]);
return (
<Container className="small-container">
<Helmet>
<title>Sign Up</title>
</Helmet>
<h1 className="my-3">Sign Up</h1>
<Form onSubmit={submitHandler}>
<Form.Group className="mb-3" controlId="name">
<Form.Label>Name</Form.Label>
<Form.Control
type="name"
onChange={(e) => setName(e.target.value)}
required
/>
</Form.Group>
<Form.Group className="mb-3" controlId="email">
<Form.Label>Email</Form.Label>
<Form.Control
type="email"
onChange={(e) => setEmail(e.target.value)}
required
/>
</Form.Group>
<Form.Group
className="mb-3"
onChange={(e) => setPassword(e.target.value)}
controlId="password"
>
<Form.Label>Password</Form.Label>
<Form.Control type="password" required />
</Form.Group>
<Form.Group className="mb-3" controlId="confirmPassword">
<Form.Label>Confirm Password</Form.Label>
<Form.Control
type="password"
onChange={(e) => setConfirmPassword(e.target.value)}
required
/>
</Form.Group>
{msg && <div className="mb-3">{msg}</div>}
{error && <div className="mb-3">{error}</div>}
<div className="mb-3">
<Button type="submit">Sign Up</Button>
</div>
<div className="mb-3">
New customer? <Link to={`/signin?redirect=${redirect}`}>Sign In</Link>
</div>
</Form>
</Container>
);
}
/frontend/src/screens/VerifyEmailScreen.js
import React, { useContext, useState, useEffect } from 'react';
import Container from 'react-bootstrap/Container';
import Button from 'react-bootstrap/Button';
import { Helmet } from 'react-helmet-async';
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom';
import axios from 'axios';
import { Store } from '../Store';
import { toast } from 'react-toastify';
import { getError, API_URL } from '../utils';
axios.defaults.withCredentials = true;
export default function VerifyEmailScreen() {
const navigate = useNavigate();
const { search } = useLocation();
const params = useParams();
const redirectInUrl = new URLSearchParams(search).get('redirect');
const redirect = redirectInUrl ? redirectInUrl : '/:id/verify/:token';
const [validUrl, setValidUrl] = useState('');
const { state, dispatch: ctxDispatch } = useContext(Store);
const { userInfo } = state;
const [msg, setMsg] = useState('');
useEffect(() => {
const verifyEmailUrl = async () => {
try {
const url = await axios.get(
`/api/users/${params.id}/verify/${params.token}`
);
console.log(url);
ctxDispatch({ type: 'USER_SIGNIN', payload: url });
localStorage.setItem('userInfo', JSON.stringify(url));
setMsg(url.message);
setValidUrl(true);
} catch (error) {
getError(error);
setValidUrl(false);
}
};
verifyEmailUrl();
});
return (
<Container className="small-container">
<Helmet>
<title>Sign Up</title>
</Helmet>
{validUrl ? (
<div className="d-flex justify-content-center flex-column text-center">
<h1 className="mb-5">Email Verified successfully</h1>
{msg && <div className="mb-3">{msg}. Please Login below</div>}
<Link to="/login">
<Button>Login</Button>
</Link>
</div>
) : (
<h1>404 Not Found</h1>
)}
</Container>
);
}
App.js //it is at this point I get a bad request response
<Route
path="/:id/verify/:token"
element={<VerifyEmailScreen />}
/>
backend server is running at port 5111 while frontend server is on port 3000 and I have set proxy in frontend package.json to port 5111. Please help pls
I solve this issue by replacing _id with userId in the url link that was being sent to the user email in the backend. I was already passing the user's id to the userId in the verifyToken function and then passing the verifyToken._id to the url link to sent.
Replace:
const verifyToken = await new VerificationToken({
userId: user._id,
token: crypto.randomBytes(32).toString('hex'),
}).save();
const url = `${process.env.BASE_URL}/${verifyToken._id}/verify/${verifyToken.token}`;
With:
const verifyToken = await new VerificationToken({
userId: user._id,
token: crypto.randomBytes(32).toString('hex'),
}).save();
const url = `${process.env.BASE_URL}/${verifyToken.userId}/verify/${verifyToken.token}`;
I solved the problem and should add an error message "Uncaught (in promise) SyntaxError: Unexpected end of JSON input"
When creating a new user, got the error 400
It was fine locally but doesn't work after deployed
**Note: The database in Heroku is different from Railway, there's no varchar in Railway, use text instead
I deployed react in Netlify and Express & Postgresql db in Railway
I doubted it was from the setUser part, but I have no clue what the problem is
Does it relate to useContext, cuz setUser is from there?
**Note: setUser is not the problem
// front-end sign up
import React, { useState, useContext } from "react";
import { useNavigate } from "react-router-dom";
import Button from "../Button";
import { Wrapper } from "./Signup.styles";
import { Context } from "../../context";
const Signup = () => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState(false);
const [user, setUser] = useContext(Context);
const navigate = useNavigate();
const handleSubmit = () => {
if (!username || !password || !email) return setError(true);
try {
fetch("https://react-rmdb-backend-production.up.railway.app/signup", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username: username,
email: email,
password: password
})
})
.then(res => res.json())
.then(user => {
if (user.id) {
setUser({
id: user.id,
username: user.username,
email: user.email
});
navigate("/");
}
});
} catch (error) {
setError(true);
}
};
const handleInput = e => {
const name = e.target.name;
const value = e.target.value;
if (name === "username") setUsername(value);
if (name === "password") setPassword(value);
if (name === "email") setEmail(value);
};
return (
<Wrapper>
{error && <div className="error">Oops! Something went wrong!</div>}
<h2>Sign Up</h2>
<label htmlFor="username">Username:</label>
<input
type="text"
value={username}
name="username"
onChange={handleInput}
/>
<label htmlFor="email">Email:</label>
<input type="email" value={email} name="email" onChange={handleInput} />
<label htmlFor="password">Password:</label>
<input
type="password"
value={password}
name="password"
onChange={handleInput}
/>
<Button text="Signup" callback={handleSubmit} />
</Wrapper>
);
};
export default Signup;
// back-end sign up
const handleSignup = (req, res, db, bcrypt) => {
const { username, email, password } = req.body;
if (!email || !username || !password) {
return res.status(400).json("Something went wrong");
}
const saltRounds = 10;
const hash = bcrypt.hashSync(password, saltRounds);
db.transaction((trx) => {
trx
.insert({
hash: hash,
email: email,
})
.into("login")
.returning("email")
.then((loginEmail) => {
return trx("users")
.returning("*")
.insert({
username: username,
email: loginEmail[0].email,
})
.then((user) => {
// should use res.json(user[0])
res.send(user[0]);
});
})
.then(trx.commit)
.catch(trx.rollback);
}).catch((err) => res.status(400).json("unable to sign up"));
};
module.exports = {
handleSignup,
};
Any advice would be appreciated.
I am having an issue with my React Redux and Node app. I am trying to Log in an existing user but in my console i am getting the following error:
Uncaught (in promise) TypeError: error.response.data is undefined
The console points to the following block of code:
export const login = (email, password) => async (dispatch) => {
const body = { email, password };
try {
const res = await axios.post('http://localhost:5000/api/auth', body);
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
});
dispatch(loadUSer());
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
}
dispatch({
type: LOGIN_FAIL
});
}
};
This is my server side for user auth auth.js:
const express = require('express');
const router = express.Router();
const User = require('../../models/User');
const auth = require('../../middleware/auth');
const config = require('config');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { check , validationResult } = require('express-validator/');
//#route GET api/auth
//#desc Test route
//#access public
router.get('/',auth, async(req, res)=> {
try{
const user = await User.findById(req.user.id).select('-password');
res.json(user);
}catch(err){
console.error(err.message);
res.status(500).send('Server Error');
}
});
//#route POST api/auth
//#desc Authenticate user & get token
//#access public
router.post('/', [
check('email', 'Plese include a valid email').isEmail(),
check('password', 'Password is required').exists()
],
async (req, res)=> {
const errors = validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({ errors:errors.array()}); //400 is for bad requests
}
const { email, password } = req.body;
try{
//See if user exists
let user = await User.findOne({ email });
if(!user){
return res.status(400).json({ errors: [{ msg:'Invalid credentials' }] });
}
//Compare the input password, plane text, to the encrypted password.
const isMatch = await bcrypt.compare(password, user.password);
if(!isMatch){
return res.status(400).json({ errors: [{ msg:'Invalid credentials' }] });
}
//Return jsonwebtoken -> this for users to be logged in right after registration
const payload = {
user:{
id: user.id
}
}
jwt.sign(
payload,
config.get('jwtSecret'),
{expiresIn: 360000}, //change to 3600 for production
(err, token)=>{
if(err) throw err;
res.json({ token });
}
)
}catch(err){
console.error(err.message);
res.status(500).send('Server Error');
}
});
module.exports = router;
And this is my Login component:
import React, { Fragment, useState } from 'react'
/* import axios, { Axios } from 'axios'; */
import { Link, Navigate } from 'react-router-dom'
import { connect } from 'react-redux';
import { PropTypes } from 'prop-types';
import { login } from '../../actions/auth';
const Login = ({ login, isAuthenticated }) => {
const [formData, setFormData] = useState({
email: '',
password: ''
});
const { email, password } = formData;
const onChange = e => setFormData({
...formData, [e.target.name]:e.target.value
});
const onSubmit = async e => {
e.preventDefault();
login(email, password);
}
//Redirect if logged in
if(isAuthenticated){
return <Navigate to="/dashboard"/>;
}
return (
<Fragment>
<section className='container'>
<h1 className="large text-primary">Sign Up</h1>
<p className="lead"><i className="fas fa-user"></i> Sign Into Your Account</p>
<form className="form" action="create-profile.html" onSubmit={e => onSubmit(e)}>
<div className="form-group">
<input type="email"
placeholder="Email Address"
name="email" value={email}
onChange={e => onChange(e)}
required/>
</div>
<div className="form-group">
<input
type="password"
placeholder="Password"
name="password"
minLength="6"
value={password}
onChange={e => onChange(e)}
required
/>
</div>
<input type="submit" className="btn btn-primary" value="Login" />
</form>
<p className="my-1">
Don´t have an account? <Link to="/register">Sign up</Link>
</p>
</section>
</Fragment>
)
}
Login.propTypes = {
login: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool
}
const mappedStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated
})
export default connect(mappedStateToProps , { login })(Login)
For some reason there are sometimes i am able to login and sometimes i encounter this issue but i cannot figure out what am i doing wrong.
My redux devtools also show the AUTH_ERROR action type:
This is my auth.js in my actions directory.
export const loadUSer = () => async dispatch => {
if(localStorage.token){
setAuthToken(localStorage.token);
}
try {
const res = await axios.get('http://localhost:5000/api/auth');
dispatch({
type: USER_LOADED,
payload: res.data
})
} catch (error) {
dispatch({
type:AUTH_ERROR
})
}
}
auth.js (reducers directory):
import{
REGISTER_FAIL,
REGISTER_SUCCESS,
USER_LOADED,
AUTH_ERROR,
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGOUT
} from '../actions/types'
const initialState = {
token: localStorage.getItem('token'),
isAuthenticated: null,
loading: true,
user: null
}
function authReducer(state = initialState, action){
const { type, payload } = action
switch (type) {
case USER_LOADED:
return {
...state,
isAuthenticated:true,
loading: false,
user:payload
}
case LOGIN_SUCCESS:
case REGISTER_SUCCESS:
localStorage.setItem('token', payload.token);
return {
...state,
...payload,
isAuthenticated: true,
loading: false
}
case LOGOUT:
case LOGIN_FAIL:
case REGISTER_FAIL:
case AUTH_ERROR:
localStorage.removeItem('token');
return {
...state,
toke: null,
isAuthenticated: false,
loading: false
}
default:
return state;
}
}
export default authReducer
So i first log in with an user everything works fine, i logout and log in with a different user and also works, i now logout and want to login to the first user again and the error shows up. The only difference between both users is that one has a profile and the other one doesn´t.
When i try to log in with the user with no profile my app crashes and my vscode terminal shows a different errors:
Can't set headers after they are sent to the client
Hi, I'm new to this react and koa. Is this code correct? I'm trying to create react and koa projects from scratch. I have a react project. I would like to create a downloadable windows exe. I can do it with a node server using Zeit pkg but I don't know how to do that (or something similar) with react.
I have tried Zeit pkg. Not seeing many other options.
Backend
server.js
require('dotenv').config();
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const cors = require('#koa/cors');
const { dbConnect } = require('./utills/dbConnect.js');
const app = new Koa();
app.use(cors());
app.use(bodyParser());
//routers
const userRouter = require('./routes/user.router.js');
app.use(userRouter.routes())
.use(userRouter.allowedMethods());
const vehicleRouter = require('./routes/vehicle.router.js');
app.use(vehicleRouter.routes())
.use(userRouter.allowedMethods());
app.listen(8080, () => {
dbConnect();
console.log("Application running on port 8080");
});
//Installed packages
// #koa/cors
// #koa/router
// dotenv
// jsonwebtoken
// koa
// koa-bodyparser
// mongoose
// nodemon
model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
id: {type:String, required:true},
name: {type:String, required:true},
email: {type:String, required:true},
password:{type:String, required:true}
});
const User = mongoose.model("User", userSchema);
module.exports = User;
Controller
const jwt = require('jsonwebtoken');
const User = require("../models/user.model");
const getAllUsers = async (ctx)=>{
await User.find().then((users)=>{
ctx.body = users;
}).catch((err)=>{
console.log(err);
})
}
const addUser = async (ctx)=>{
const {id, name, email, password} = ctx.request.body;
const newUser = new User({id, name, email, password});
const user = await User.create(newUser);
if(user){
ctx.body = user;
ctx.set('Content-Type', 'application.json');
ctx.status = 201;
} else {
ctx.body = {status:"error occured"}
ctx.set('Content-Type', 'application.json');
}
}
const updateUser = async (ctx)=>{
const uid = ctx.params.id;
const {id, name, email, password} = ctx.request.body;
const updateUser = {id, name, email, password}
await User.findByIdAndUpdate(uid, updateUser).then(()=>{
ctx.body = {status:"User Updated"};
}).catch((err)=>{
console.log(err);
ctx.body = {status:"Error occured"}
})
}
const deleteUser = async (ctx)=>{
const uid = ctx.params.id;
await User.findByIdAndDelete(uid).then(()=>{
ctx.body = {status:"User Deleted"};
}).catch((err)=>{
console.log(err);
ctx.body = {status:"Error occured"}
})
}
const login = async (ctx)=>{
const {email, password} = ctx.request.body;
const user = await User.findOne({email});
console.log(user)
if(user && (password == user.password)){
const token = jwt.sign(
{
_id: user._id,
name: user.name,
email: user.email,
password: user.password
},
'SecretKey123'
)
return ctx.body = {token:token}
} else {
return ctx.body = {status:'Login Failed'}
}
}
const auth = async (req, res)=>{
const token = req.headers['x-access-token']
try {
const decoded = jwt.verify(token, 'secret123')
const _id = decoded._id
const user = await User.findById(_id);
return res.json({ status: 'ok', name: user.name, role: user.role, id: user._id, subRole: user.subRole, uid:user.id, user:user })
} catch (error) {
console.log(error)
res.json({ status: 'error', error: 'invalid token' })
}
}
module.exports = {addUser, updateUser, deleteUser, getAllUsers, login, auth}
Router
const Router = require('#koa/router');
const { addUser, getAllUsers, updateUser, deleteUser, login, auth } = require('../controller/user.controller');
const userRouter = new Router({
prefix: '/users'
});
userRouter.get('/',getAllUsers);
userRouter.post('/add',addUser);
userRouter.put('/update/:id', updateUser);
userRouter.delete('/delete', deleteUser);
userRouter.post('/login', login);
userRouter.post('auth', auth)
module.exports = userRouter;
DB Connect
const mongoose = require('mongoose');
const dbConnect = () => {
const dbConStr = process.env.MONGODB_URL;
mongoose.connect(dbConStr, (connection)=>{
console.log("MongoDB Connection Success");
})
}
module.exports = {dbConnect}
Frontend
App.js
import logo from './logo.svg';
import './App.css';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom'
import HeaderComponent from './components/HeaderComponent';
import Register from './pages/Register';
import Users from './pages/Users';
import Login from './pages/Login';
function App() {
return (
div className='container'>
HeaderComponent/>
Router>
Routes>
Route exact path="/" element={Users/>}/>
Route exact path="/register" element={Register/>}/>
Route exact path="/login" element={Login/>}/>
/Routes>
/Router>
/div>
);
}
export default App;
Login.jsx
import axios from "axios";
import React,{useEffect, useState} from "react";
function Login() {
//User Details
const[email, setEmail] = useState('');
const[password, setPassword] = useState('');
function loginUserHandler(e) {
e.preventDefault();
const user = { email, password }
axios.post('http://localhost:8080/users/login', user).then((res)=>{
if(res.data.token){
sessionStorage.setItem("isLogged", true);
window.location="/";
} else {
window.location.reload(false)
alert("login failed")
}
}).catch((err)=>{
console.log(err);
})
}
return (
div>
h2 className="text-center mt-3">Login/h2>
div>
form style={{width:"50%", margin:"auto"}}>
div className="form-group">
label>Email : /label>
input type="email" className="form-control" onChange={(e)=>setEmail(e.target.value)} />
/div>
div className="form-group">
label>Password : /label>
input type="password" className="form-control" onChange={(e)=>setPassword(e.target.value)} />
/div>
div className="text-center mt-2">
button className="btn btn-primary" onClick={loginUserHandler}>Login/button>
/div>
/form>
/div>
/div>
);
}
export default Login;
Register.jsx
import axios from "axios";
import React,{useEffect, useState} from "react";
function Register() {
//User Details
const[name, setName] = useState('');
const[email, setEmail] = useState('');
const[id, setId] = useState('');
const[password, setPassword] = useState('');
function registerUserHandler(e) {
e.preventDefault();
const user = {name, email, password, id}
axios.post('http://localhost:8080/users/add', user).then(()=>{
alert('User added');
}).catch((err)=>{
console.log(err);
})
}
return (
div>
h2 className="text-center mt-3">Register/h2>
div>
form style={{width:"50%", margin:"auto"}}>
div className="form-group">
label>Name : /label>
input type="text" className="form-control" onChange={(e)=>setName(e.target.value)} />
/div>
div className="form-group">
label>Email : /label>
input type="email" className="form-control" onChange={(e)=>setEmail(e.target.value)} />
/div>
div className="form-group">
label>ID : /label>
input type="text" className="form-control" onChange={(e)=>setId(e.target.value)} />
/div>
div className="form-group">
label>Password : /label>
input type="password" className="form-control" onChange={(e)=>setPassword(e.target.value)} />
/div>
div className="text-center mt-2">
button className="btn btn-primary" onClick={registerUserHandler}>Register/button>
/div>
/form>
/div>
/div>
);
}
export default Register;
Hey I am trying to build a simple Login and Profile seeing app. Where you can Register and Login and after that it will take you to your Profile where whatever you wrote in the Registration will show. But i am stuck, I need this for my internship plase anyone help me?? Below I am posting API and front end code.
server.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const userRouter = require('./routes/user.route');
const loginRouter = require('./routes/login.route');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(express.json());
app.use(cors());
const uri = process.env.ATLAS_URI;
mongoose
.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then((res) =>
console.log('MongoDb connected .....')
)
.catch((err) => console.log(err));
app.use('/users', userRouter);
app.use('/login', loginRouter);
app.listen(port, () => {
console.log(`App is running on port ${port}`);
});
user.route.js
const express = require('express');
const Router = express.Router();
const User = require('../models/user.model');
Router.route('/').get((req, res) => {
User.find()
.then((response) => res.json(response))
.catch((err) =>
res.status(400).json('Error: ' + err)
);
});
Router.route('/add').post((req, res) => {
const {
firstname,
lastname,
email,
contact,
password,
} = req.body;
const newUser = new User({
firstname,
lastname,
email,
contact,
password,
});
newUser
.save()
.then((response) => res.json(response))
.catch((err) =>
res.status(400).json('Error: ' + err)
);
});
Router.route('/:id').get((req, res) => {
User.findById(req.params.id)
.then((response) => res.json(response))
.catch((err) => res.json(err));
});
module.exports = Router;
login.route.js
const express = require('express');
const Router = express.Router();
const User = require('../models/user.model');
Router.route('/').post((req, res) => {
User.findOne({ email: req.body.email })
.then((user) => {
if (user) {
if (req.body.password === user.password) {
return res.json(user);
} else {
return res.json('wrong password');
}
} else {
return res.json('User not found');
}
})
.catch((err) => res.json('Error: ' + err));
});
module.exports = Router;
Front End
app.js
import React, { Component } from 'react';
import { BrowserRouter } from 'react-router-dom';
import { Route } from 'react-router';
import Login from './components/login';
import Signup from './components/signup';
import Profile from './components/profile';
export default class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Route
path='/'
exact
component={Login}
/>
<Route
path='/signup'
exact
component={Signup}
/>
<Route
path='/users/:id'
component={Profile}
/>
</div>
</BrowserRouter>
);
}
}
login.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
export default class Login extends Component {
constructor() {
super();
this.state = {
email: '',
password: '',
};
}
onChangeEmail = (event) => {
this.setState({
email: event.target.value,
});
};
onChangePassword = (event) => {
this.setState({
password: event.target.value,
});
};
handleSubmit = (event) => {
event.preventDefault();
const newLogin = {
email: this.state.email,
password: this.state.password,
};
axios
.post(
'http://localhost:5000/login',
newLogin
)
.then((res) => {
window.location =
'/users/' + res.data._id;
})
.catch((err) => console.log(err));
this.setState({
email: '',
password: '',
});
};
render() {
return (
<div
className='container'
style={{ width: '400px' }}>
<div style={{ marginTop: '200px' }}>
<form onSubmit={this.handleSubmit}>
<div className='mb-3'>
<label
htmlFor='Email'
className='form-label'>
Email address
</label>
<input
value={this.state.email}
onChange={this.onChangeEmail}
type='email'
className='form-control'
id='Email'
aria-describedby='emailHelp'
/>
<div
id='emailHelp'
className='form-text'>
We'll never share your email with
anyone else.
</div>
</div>
<div className='mb-3'>
<label
htmlFor='Password'
className='form-label'>
Password
</label>
<input
value={this.state.password}
onChange={this.onChangePassword}
type='password'
className='form-control'
id='Password'
/>
</div>
<div>
{`Dont have an account? Click `}
<Link to='/signup'>Here</Link>
</div>
<button
type='submit'
className='btn btn-primary'>
Submit
</button>
</form>
</div>
</div>
);
}
}
profile.js
import axios from 'axios';
import React, { Component } from 'react';
export default class Profile extends Component {
constructor() {
super();
this.state = {
Name: '',
LastName: '',
email: '',
};
}
componentDidMount() {
axios
.get('http://localhost:5000/users/')
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
}
render() {
return (
<div>
<h1>Name</h1>
<h3>LastName</h3>
<p>email</p>
</div>
);
}
}
res.redirect('/your_page')
Use this when the user is saved in the database or when user is successfully authenticated