Closed romebell closed 3 years ago
// server
(node:58250) UnhandledPromiseRejectionWarning: TypeError: res.return is not a function
at /Users/User/Desktop/SEI1019/unit_3/codealong/mern-auth-backend/controllers/users.js:58:23
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:58250) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:58250) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
// users.js
require('dotenv').config();
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken')
const passport = require('passport');
const JWT_SECRET= process.env.JWT_SECRET
// Models
const db = require('../models');
// GET api/users/test (Public)
router.get('/test', (req, res) => {
res.json({ msg: 'User endpoint OK!'});
});
// POST api/users/register (Public)
router.post('/register', (req, res) => {
console.log('inside of register')
console.log(req.body);
console.log(db);
db.User.findOne({ email: req.body.email })
.then(user => {
// if email already exits, send a 400 response
console.log(user);
if (user) {
return res.status(400).json({ msg: 'Email already exists' });
} else {
// Create a new user
console.log('else statement');
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
// Salt and hash the password, then save the user
bcrypt.genSalt(10, (err, salt) => {
// if (err) throw Error;
bcrypt.hash(newUser.password, salt, (error, hash) => {
// if (error) throw Error;
// Change the password in newUser to the hash
newUser.password = hash;
newUser.save()
.then(createdUser => res.json(createdUser))
.catch(err => console.log(err));
})
})
}
})
})
router.post('/login', (req, res)=>{
const email = req.body.email;
const password = req.body.password;
db.User.findOne({ email })
.then(user =>{
console.log(user)
if(!user){
res.status(400).json({msg: 'User not found'})
}else{
bcrypt.compare(password, user.password)
.then(isMatch => {
if(isMatch){
console.log(isMatch)
const payload={
id: user.id,
email: user.email,
name: user.name
}
jwt.sign(payload, JWT_SECRET, {expiresIn: '1h'},(error, token)=>{
res.json({
success: true,
token: `Bearer ${token} `
})
})
}else{
return res.status(400).json({ msg: 'Email or password is incorrect'})
}
})
}
})
})
module.exports = router;
// Imports
require('dotenv').config();
const express = require('express');
const app = express();
const cors = require('cors');
const passport = require('passport');
require('./config/passport')(passport);
const PORT = process.env.PORT || 8000;
// API
const users = require('./api/users');
// Middleware
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(passport.initialize());
app.get('/', (req, res) => {
res.status(200).json({ message: 'Smile, you are being watched by the Backend Engineering Team' });
});
app.use('/api/users', users);
app.listen(PORT, () => {
console.log(`Server is listening 🎧 on port: ${PORT}`);
});
// Imports
require('dotenv').config();
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken')
const passport = require('passport');
const JWT_SECRET = process.env.JWT_SECRET;
console.log(JWT_SECRET);
// Models
const db = require('../models');
// GET api/users/test (Public)
router.get('/test', (req, res) => {
res.json({ msg: 'User endpoint OK!'});
});
// POST api/users/register (Public)
router.post('/register', (req, res) => {
console.log('inside of register')
console.log(req.body);
console.log(db);
db.User.findOne({ email: req.body.email })
.then(user => {
// if email already exits, send a 400 response
console.log(user);
if (user) {
return res.status(400).json({ msg: 'Email already exists' });
} else {
// Create a new user
console.log('else statement');
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
// Salt and hash the password, then save the user
bcrypt.genSalt(10, (err, salt) => {
// if (err) throw Error;
bcrypt.hash(newUser.password, salt, (error, hash) => {
// if (error) throw Error;
// Change the password in newUser to the hash
newUser.password = hash;
newUser.save()
.then(createdUser => res.json(createdUser))
.catch(err => console.log(err));
})
})
}
})
})
router.post('/login', (req, res) => {
const email = req.body.email;
const password = req.body.password;
db.User.findOne({ email })
.then(user => {
if (!user) {
res.status(400).json({ msg: 'User not found'});
} else {
bcrypt.compare(password, user.password)
.then(isMatch => {
if (isMatch) {
const payload = {
id: user.id,
email: user.email,
name: user.name
};
jwt.sign(payload, JWT_SECRET, { expiresIn: 3600 }, (error, token) => {
res.json({
success: true,
token: 'Bearer ${token}'
});
});
} else {
return res.status(400).json{{ msg: 'Email or password is incorrect' }};
}
})
}
})
})
module.exports = router;
Include this in users.js:
const { JWT_SECRET } = require('../config/keys')
@marjames98 replace line 8 with the line above
@andrewemcmanus like this?
@marjames98 yeah. And the keys.js file in the config folder should be:
JWT_SECRET: "sei1019isthecoolestever",
MONGO_URI: "mongodb://127.0.0.1:27017/mernAuth"
}
module.exports = keys;
Sorry! it's this:
const keys = {
JWT_SECRET: "sei1019isthecoolestever",
MONGO_URI: "mongodb://127.0.0.1:27017/mernAuth"
}
module.exports = keys;
@romebell RESOLVED
Please add issues here.