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;
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'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', {
I have a Sign Up modal in my React Bootstrap App to allow registration for new users. I set an onChange event for each attributes to be stored in the database and user should be saved to database if the button Sign Up is clicked, triggering the onClick button. The problem is, the user won't be saved to Mongodb at all. I'm certain the problem is within the SignUpModal code since I did try passing it via node.js on index.js and it worked. The codes are below:
SignUpModal.js (client side)
const [userEmail, setEmail] = useState("");
const [userPassword, setPassword] = useState("");
const [userFullName, setFullName] = useState("");
const [userType, setType] = useState("");
//add user to database
const addUser = () => {
Axios.post("/addUser", {
userEmail: userEmail,
userPassword: userPassword,
userFullName: userFullName,
userType: userType,
});
};
return(
<Modal
{...props}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">
Sign Up Form
</Modal.Title>
</Modal.Header>
<Form>
<Modal.Body>
<Form.Group className="mb-3" controlId="userEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter your email here"
onChange = {(event) => {
setEmail(event.target.value);
}}
/>
</Form.Group>
<Form.Group className="mb-3" controlId="userPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="Enter your password here"
onChange = {(event) => {
setPassword(event.target.value);
}}
/>
</Form.Group>
<Form.Group className="mb-3" controlId="userFullName">
<Form.Label>Full Name</Form.Label>
<Form.Control type="text" placeholder="Enter full name here"
onChange = {(event) => {
setFullName(event.target.value);
}}
/>
</Form.Group>
<Form.Group className="mb-3" controlId="formType">
<Form.Label>I am a... (Tick one of the options below):</Form.Label>
{['radio'].map((type) => (
<div key={`inline-${type}`} className="mb-3">
<Form.Check
inline
label="Client"
name="group1"
type={type}
id={`inline-${type}-1`}
onChange = {(event) => {
setType(event.target.value);
}}
/>
<Form.Check
inline
label="Service provider"
name="group1"
type={type}
id={`inline-${type}-2`}
onChange = {(event) => {
setType(event.target.value);
}}
/>
</div>
))}
</Form.Group>
</Modal.Body>
<Modal.Footer>
<Button onClick={props.onHide}>Close</Button>
<Button variant="primary" type="submit" onClick= {addUser}>
Sign Up!
</Button>
</Modal.Footer>
</Form>
</Modal>
)
}
index.js (server side)
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const UserModel = require("./models/User");
const cors = require("cors");
app.use(express.json());
app.use(cors());
mongoose.connect("mongodb+srv://tryweb:password1234#cluster5.c58gv.mongodb.net/user?retryWrites=true&w=majority",
{
useNewUrlParser: true,
});
app.post("/addUser", async(req, res) => {
const user = new UserModel(
{ userEmail: req.body.userEmail,
userPassword: req.body.userPassword,
userFullName: req.body.userFullName,
userType: req.body.userType
}
);
try{
await user.save();
}
catch(err){
console.log(err);
}
});
app.listen(3000, () => {
console.log("Server running in port 3000...");
});
I have tried changing the URL to http://localhost:3000/addUser and it still does not work. Anyone knows what I am doing wrong?
This looks good, but you might be hitting an error with the data or within the browser. Try logging the data as it comes into the request with console.log(req.body).
Try this:
Assuming that your ./models/User looks something like this:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let User = new Schema(
{
userEmail: {
type: String
},
userPassword: {
type: String
},
userFullName: {
type: String
},
userType: {
type: String
}
},
{ collection: "Users" }
);
module.exports = mongoose.model("User", User);
And the code:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const UserModel = require("./models/User");
const cors = require("cors");
app.use(express.json());
app.use(cors());
const mongooseConnectionString = "mongodb+srv://tryweb:password1234#cluster5.c58gv.mongodb.net/user?retryWrites=true&w=majority";
const mongooseConnection = mongoose.connect(mongooseConnectionString,
{
useNewUrlParser: true,
});
// Let us know we established connection
mongooseConnection.once("open", function() {
console.log("MongoDB database connection established successfully");
});
app.post("/addUser", async(req, res) => {
const user = new UserModel(req.body);
try{
await user.save();
response.send(user);
}
catch(err){
console.log(err);
response.status(500).send(error);
}
});
app.listen(3000, () => {
console.log("Server running in port 3000...");
});
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