I am facing an error while making the POST SignUp request.
I had deployed the frontend on Netlify here and the backend on Heroku here.
Error
I am getting 2 errors:
-
I am getting
`users.findOne()` buffering timed out after 10000ms
-
I am getting this on console
SyntaxError: Unexpected token i in JSON at position 0
Code
Attached is the code in the flow
index.js
const connectToMongo = require('./db');
const express = require('express');
connectToMongo();
var cors = require('cors')
const app = express()
// const port = 5000
//to use req body
app.use(cors())
app.use(express.json())
//Available routes
app.use('/api/auth',require('./routes/auth'));
app.use('/api/notes',require('./routes/notes'));
app.listen(process.env.PORT , () => {
console.log(`my-notebook backend listening at https://my-notebook-mohit.herokuapp.com:${process.env.PORT }`)
})
auth.js (see only route1)
const express = require("express");
const { body, validationResult } = require("express-validator");
const router = express.Router();
const User = require("../models/User");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const JWT_SECRET = "mohitisagood$boy";
const fecthUser = require("../middleware/fetchUser");
//ROUTE 1 :Creating a User :POST - "/api/auth/createuser"
router.post(
"/createuser",
[
body("name", "Name must have at least 3 characters").isLength({ min: 3 }),
body("email", "Enter a valid email").isEmail(),
],
async (req, res) => {
let success = false;
//If there are errors, then return bad request + Errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({success, errors: errors.array() });
}
try {
//Check whether email exists
let user = await User.findOne({ email: req.body.email });
//console.log("user.nemail = " + user);
if (user) {
//console.log(user.email);
return res.status(400).json({success, error: "Email Already Taken" });
}
//hashing the password here
const salt = await bcrypt.genSalt(10);
const secPass = await bcrypt.hash(req.body.password, salt);
//user is created
user = await User.create({
name: req.body.name,
email: req.body.email,
password: secPass,
});
//passing the id as data to make jwt token
const data = {
user: {
id: user.id,
},
};
const authToken = jwt.sign(data, JWT_SECRET);
//console.log(authToken)
success = true;
//res.json(user);
res.json({success, authToken });
} catch (error) {
console.log(error.message);
res.status(500).send("internal server error");
}
}
);
//ROUTE 2 :Authenticating a User :POST - "/api/auth/login"
router.post(
"/login",
.......
)
});
module.exports = router;
MODEL_SCHEMA – users
const mongoose = require("mongoose");
const { Schema } = mongoose;
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
validate(value) {
if(value.length < 5) {
throw new Error( "Minimum length is 5 characters");
}
else if (!value.match(/d/) || !value.match(/[a-zA-Z]/) ) {
throw new Error(
"Password must contain at least one letter and one number"
);
}
}
},
date: {
type: Date,
default: Date.now,
},
});
const User = mongoose.model("users", UserSchema);
module.exports = User;
SignUpPage.js (frontEnd)
import React,{useState} from 'react';
import { useHistory } from 'react-router-dom';
import imgpath from "../assets/notepic.jpg";
import { motion } from 'framer-motion';
const Signup = (props) => {
let history = useHistory();
const [credentials, setCredentials] = useState({name:"", email:"", password:"",confmpassword:""});
const onChange = (e) => {
setCredentials({ ...credentials, [e.target.name]: e.target.value });
//input mei value typed ho sake,jaise jaise value change ho vese-vese note me set ho jaye
};
const goToLogin = () => {
history.push("/login")
}
const handleSubmit = async(e) => {
e.preventDefault();
const response = await fetch('https://my-notebook-mohit.herokuapp.com:/api/auth/createuser', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({name:credentials.name, email:credentials.email, password: credentials.password})
});
const json = await response.json();
if(json.success === true){
//storing the authtoken
localStorage.setItem('token',json.authToken);
history.push("/");
console.log(json);
props.showAlert("User registered succesfully!","info");
}
else {
props.showAlert("Invalid Credentials","danger");
}
}
return (
<motion.div className="container" id="manku" animate={{scale:[0.5,1]}} transition={{times:[0.1,0.4], ease:'easeInOut'}}>
<div id="picturebody">
<img src={imgpath} alt="note-pic" width="100%" />
</div>
<div id="loginbody">
<div className="mt-3">
<h2 className="my-2">Create your account here </h2>
<form onSubmit={handleSubmit} className="login-form">
..
..
..
</form>
<div className="text-center my-3" id="bottom-text">
mynotebook
</div>
</div>
</div>
</motion.div>
)
}
export default Signup
I am also sharing the HEROKU LOGS here also
Screenshot
In written form:
2022-01-22T10:35:31.575900+00:00 app[web.1]: > [email protected] start
2022-01-22T10:35:31.575901+00:00 app[web.1]: > node index.js
2022-01-22T10:35:31.575901+00:00 app[web.1]:
2022-01-22T10:35:32.186481+00:00 heroku[web.1]: State changed from starting to up
2022-01-22T10:35:32.002450+00:00 app[web.1]: my-notebook backend listening at https://my-notebook-mohit.herokuapp.com:23186
2022-01-22T10:36:01.901941+00:00 app[web.1]: Connected to Mongo Successfully!
2022-01-22T10:37:28.170226+00:00 heroku[router]: at=info method=OPTIONS path="/api/auth/createuser" host=my-notebook-mohit.herokuapp.com request_id=ca6d3e38-ca85-4b8d-834c-2503743f261e fwd="157.34.191.86" dyno=web.1 connect=0ms service=5ms status=204 bytes=301 protocol=https
2022-01-22T10:37:29.785982+00:00 app[web.1]: Cannot read properties of undefined (reading 'findOne')
2022-01-22T10:37:29.788991+00:00 heroku[router]: at=info method=POST path="/api/auth/createuser" host=my-notebook-mohit.herokuapp.com request_id=3f713497-80fb-45e1-a73c-c25fa7f03c4e fwd="157.34.191.86" dyno=web.1 connect=0ms service=25ms status=500 bytes=272 protocol=https
2022-01-22T10:54:57.762199+00:00 heroku[router]: at=info method=GET path="/api/auth/createuser" host=my-notebook-mohit.herokuapp.com request_id=ae666363-1d9c-4d9e-9104-c542c7d10837 fwd="34.230.34.4" dyno=web.1 connect=0ms service=2ms status=404 bytes=434 protocol=https
2022-01-22T10:55:04.937835+00:00 heroku[router]: at=info method=HEAD path="/" host=my-notebook-mohit.herokuapp.com request_id=f132be41-83f5-4a16-9b9d-ed98dda893bf fwd="217.182.175.162" dyno=web.1 connect=0ms service=2ms status=404 bytes=276 protocol=https