I followed a tutorial and tried to implement some code from this repo https://github.com/ArjunAranetaCodes/MoreCodes-Youtube/tree/master/mern-mysql-login-reg. It takes a user's registration information and stores it in a database.
When I put in http://localhost:5000/users/register in postman I get a Cannot GET /users/register and I don't know why.
I don't know if its a problem with the database or not. I should be able to reach /users/register though shouldn't I?
server.js
const cors = require('cors');
const bodyParser = require('body-parser');
const express = require('express');
const port = process.env.PORT || 5000;
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }))
const Users = require('./routes/Users');
app.use('/users', Users)
app.listen(port, () => {
console.log('SERVER RUNNING ON PORT: ' + port);
});
database/db.js
const Sequelize = require("sequelize")
const db = {}
const sequelize = new Sequelize("accounts", "root", "password", {
host: "localhost",
dialect: "mysql",
operatorAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
})
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
models/User.js
const Sequelize = require('sequelize')
const db = require('../database/db.js')
module.exports = db.sequelize.define(
'user',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
email: {
type: Sequelize.STRING
},
username: {
type: Sequelize.STRING,
},
password: {
type: Sequelize.STRING,
},
name: {
type: Sequelize.STRING,
},
datetime: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
}
},
{
timestamps: false
}
)
routes/Users.js
const express = require('express')
const users = express.Router()
const cors = require('cors');
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt');
const User = require("../models/User")
users.use(cors());
process.env.SECRET_KEY = 'secret'
users.post('/register', (req, res) => {
const today = new Date().toDateString()
const userData = {
email: req.body.email,
username: req.body.username,
password: req.body.password,
name: req.body.name,
datetime: today
}
User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if (!user) {
bcrypt.hash(req.body.password, 10, (err, hash) => {
userData.password = hash
User.create(userData)
.then(user => {
res.json({ status: user.email + 'REGISTERED' })
})
.catch(err => {
res.send('ERROR: ' + err)
})
})
} else {
res.json({ error: "USER ALREADY EXISTS" })
}
})
.catch(err => {
res.send('ERROR: ' + err)
})
})
module.exports = users
Related
Please help review my error. I have defined my user schema but it is still undefined. I have spent hours on this error but I cannot seem to find where did I go wrong.
Here's my schema and model:
const { model, Schema } = require("mongoose");
const userSchema = new Schema({
username:String,
employeeId: String,
accessLevel: String,
role: String,
company: String,
password: String,
email: String,
createdAt: Date,
});
module.exports = model("User", userSchema);
Here's controller:
const User = require("../models/user");
const registerUser = (req, res, next) => {
let user = new User({
username: req.body.username,
employeeId: req.body.employeeId,
accessLevel: req.body.accessLevel,
role: req.body.role,
company: req.body.company,
password: req.body.password,
email: req.body.email,
createdAt: new Date(),
});
module.exports = {
registerUser
};
Here's connection to DB and server:
const express = require("express");
const mongoose = require("mongoose");
const { MONGODB } = require("./config");
const userRoute = require("./routes/userRouter");
const PORT = process.env.PORT || 4000;
mongoose
.connect(MONGODB, { useNewUrlParser: true, useUnifiedTopology: true })
.then(console.log("Database connected"))
.catch((err) => {
console.log(err);
});
const server = express();
server.use((err, req, res, next) => {
console.error(err);
res.status(err.statusCode).json(err);
});
server.use("/api/user", userRoute);
server.use(express.urlencoded({ extended: true }));
server.use(express.json());
server.listen(PORT, () => console.log(`Server is listening on ${PORT}`));
Here's router:
const express = require("express");
const usersControllers = require("../controllers/usersControllers");
const router = express.Router();
router.post("/registeruser", usersControllers.registerUser);
module.exports = router;
Post request on Postman: http://localhost:4000/api/user/registeruser
body:
{
"username": "Susan",
"employeeId": "12345",
"accessLevel": "Account Admin",
"role": "MC - Engineer",
"company": "Mello",
"password": "Choochootrain",
"email": "susan#hotmail.com"
}
Try to change the order of your middleware declarations:
const server = express();
server.use(express.urlencoded({ extended: true }));
server.use(express.json());
server.use("/api/user", userRoute);
server.use((err, req, res, next) => {
console.error(err);
res.status(err.statusCode).json(err);
});
my backend is running and im connected to mongoDB but when i send a post request from postman i get this error, i also put my network access to 0.0.0.0/0 (from anywhere) i have no idea by now what may cause this error.
this error is in my terminal:
Error: connect ETIMEDOUT 18.194.195.125:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16) { name: 'MongoNetworkError' }
and i get this error in postman:
500Internal Server Error
this is my api index file:
const express = require("express");
const app = express();
const dotenv = require('dotenv');
const mongoose = require('mongoose')
const authRoute = require("./routes/auth");
dotenv.config();
app.use(express.json());
mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}).then(console.log('Connected to MongoDB'))
.catch((err) => console.log(err));
app.use("/api/auth", authRoute);
app.listen("5000", () => {
console.log("Backend is running.");
});
and here is my auth file:
const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");
//REGISTER
router.post("/register", async (req, res) => {
try {
// making password hash
const salt = await bcrypt.genSalt(10);
const hashedPass = await bcrypt.hash(req.body.password, salt);
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: hashedPass,
});
const user = await newUser.save();
res.status(200).json(user);
} catch (err) {
res.status(500).json(err);
}
});
and my user file
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
unique: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
profilePic: {
type: String,
default: "",
},
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);
Check that your backend manages to connect to MongoDB.
Look for connection logs in your mongod terminal if you're running a server locally and check your connection string ( eg. mongodb://localhost:27017/db )
I can't find what I'm doing wrong. I already dug through a plethora of stacksoverflows but didn't find any solution.
I constantly getting MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms whenever I try to register a user. Some solutions say that I didn't connect to DATABASE. However, I get a confirm that the DB is connected successfully.
Here is the codes.
server.js
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const app = express();
const PORT = process.env.PORT || 5000;
// Init Middleware
app.use(express.json({ extended: false }));
app.use(cors());
// Bodyparser
app.use(express.urlencoded({ extended: false }));
// Connecting to mongoose
mongoose.connect(
process.env.REACT_APP_MONGO_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
},
() => {
console.log("Connected successfully to DB!");
// Listening for actions
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
}
);
// Defined Routes
app.use("/", require("./routes/index"));
app.use("/users", require("./routes/users"));
users.js
const router = express.Router();
const bcrypt = require("bcryptjs");
const User = require("../models/User");
router.get("/login", (req, res) => {
res.send("Login");
});
router.get("/register", (req, res) => {
res.send("Register");
});
// #route POST /register
// #desc Creates a user
// #access Public
router.post("/register", async (req, res) => {
try {
const { name, surname, email, password, repeatedPassword } = req.body;
if (!name || !surname || !email || !password || !repeatedPassword) {
return res.status(400).json({ msg: "Not all fields were filled." });
}
if (password !== repeatedPassword) {
return res.status(400).json({ msg: "Password doesn't match." });
}
if (password.length < 6) {
return res
.status(400)
.json({ msg: "Password should be at least 6 characters long." });
}
/*
const user = await User.findOne({ email: email });
if (user) {
return res
.status(400)
.json({ msg: "This email is already specified by another user." });
}
*/
const newUser = new User({
name,
surname,
email,
password,
});
newUser.save();
console.log(newUser);
res.json(newUser);
} catch (error) {
res.status(500).send("Server error");
}
});
module.exports = router;
User.js (model)
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
surname: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = User = mongoose.model("User", UserSchema);
include user model and create one.
const User = require('./User')
await User.create({ name, surname, email, password, })
I'm having issues with the authentication part of my app. I keep getting this "TypeError: Cannot read property 'fromAuthHeaderAsBearerToken' of undefined at Object." whenever I run my server.js file. It stops me from progressing any further.
Here is my passport.js file
const JWTStrategy = require('passport-jwt').Strategy;
const ExtractJWT = require('passport-jwt').ExtractJWT;
const User = require('../dbConnection/database.js');
const keys = require('./keys.js');
const opts = {
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey: keys.secretOrKey,
};
module.exports = passport => {
passport.use(
new JWTStrategy(opts, (jwt_payload, done) => {
User.findOne( {id: jwt_payload.id} ).then(user => {
if (user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
})
);
};
User Schema
const mysql = require('mysql2');
const Sequelize = require('sequelize');
// Initiate mysql connection
const connOptions = {
host: 'localhost',
user: 'root',
password: 'dummypassword',
database: 'countdown',
dialect: 'mysql'
};
const sequelize = new Sequelize(connOptions);
// Connect sequelize to the database
sequelize.authenticate()
.then(console.log('Connection has been successfully established'))
.catch(err => console.error('Unable to connect to the database: ', err));
// Create user model
const User = sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false
},
firstName: {
field: 'first_name',
type: Sequelize.STRING,
allowNull: false
},
lastName: {
field: 'last_name',
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
}
}, {
tableName: 'users'
});
module.exports = User;
And also my server.js file
const express = require('express');
const _ = require('lodash');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const users = require('./routes/api/users.js');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/client/public'));
app.use(cors());
// Passport Middleware
app.use(passport.initialize());
// Passport config
require('./config/passport')(passport);
// Routes
app.use('/users', users);
const port = process.env.port || 5000;
app.listen(port, () => {
console.log('Server started on port ' + port);
});
I'm so lost as I literally followed a tutorial that walked this through step by step (https://github.com/rishipr/mern-auth) although it was with MongoDB. I originally didn't use sequelize and thought that might be the issue. So I've refactored it to incorporate sequelize but it didn't solve my issue. Googling didn't help either as no one seems to have this specific issue blocking them from running the server.js file (most people I see are having issues when they make an API call).
Any help is appreciated. Thanks!
The problem is with line number 2 in passport.js file
const ExtractJWT = require('passport-jwt').ExtractJWT;
replace with
consst ExtractJWT= require('passport-jwt').ExtractJwt;
passport-jwt have a ExtractJwt class/method not ExtractJWT. Remember Javascrit is a case sensative language.
I'm trying to set up an API with MongoDB (Mongoose) with a JWT authentication. I am at the first step where I create an user in the DB.
But I encounter a problem : the async/await taking so long and never ending, while the user is not created on DB. I don't know why.
I'm testing with POSTMAN for requests. For information, when I'm starting my app, I'm getting the "connected to db !" who appear correctly.
Can someone help me please ?
app.js
'use strict';
const express = require("express"),
app = express(),
authRoutes = require('./routes/auth'),
externalRoutes = require('./routes/web'),
database = require('./database/db'),
bodyParser = require("body-parser"),
mongoose = require('mongoose')
;
require('dotenv').config();
var options = { useNewUrlParser: true, useUnifiedTopology: true };
mongoose.connect("mongodb+srv://user:password#host.mongodb.net/test?retryWrites=true&w=majority", options, () => console.log('connect to db !'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/api/user', authRoutes);
app.use('/', externalRoutes);
app.listen(8080);
auth.js
const router = require('express').Router();
const User = require('../database/schemas/User');
router.post('/register', async (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
const savedUser = await user.save((error, userDoc) => {
if (error) return res.status(400).send(error);
});
res.send({
user: savedUser._id
});
}).post('/login', (req, res) => {
});
module.exports = router;
User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
min: 6,
max: 255
},
email: {
type: String,
required: true,
max: 255,
min: 10
},
password: {
type: String,
required: true,
max: 1024
},
createdAt: {
type: Date,
default: Date.now()
},
updatedAt: {
type: Date,
default: Date.now()
},
});
module.exports = mongoose.model('User', userSchema);
In Auth.js do this instead
const router = require('express').Router();
const User = require('../database/schemas/User');
router.post('/register', async (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
try {
// if you are using await, don't pass it a callback
const savedUser = await user.save();
return res.send({
user: savedUser._id
});
} catch (error) {
// use try/catch to handle error instead of error first parameter in callback
return res.status(400).send(error);
}
}).post('/login', (req, res) => {
});
module.exports = router;
Here is a link to the documentation that shows you how to correctly use the save method. https://mongoosejs.com/docs/api.html#model_Model-save