Recently, I've encountered a strange issue with the controller for my login route. It was working perfectly fine yesterday without any hiccups, but suddenly it stopped functioning properly. Despite not making any changes to the code, it now consistently falls through to the catch block and throws an error. Strangely enough, there is no actual error being logged, leaving me uncertain about how to proceed.
This snippet shows my app.js file:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const systemRoutes = require('./routes/system');
const recipeRoutes = require('./routes/recipes');
const authRoutes = require('./routes/auth');
const app = express();
app.use(bodyParser.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*'); // Will restrict later
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
app.use('/api/system', systemRoutes);
app.use('/api/feed', recipeRoutes);
app.use('/api/auth', authRoutes);
// TODO: Implement error handling and validation
mongoose.connect('mongodb://localhost:27017/learn')
.then(result => {
app.listen(8080);
})
.catch(err => {
console.error(err);
});
And here's the relevant part of my controller logic:
exports.login = (req, res, next) => {
let fetchedUser;
User.findOne({ username: req.body.username })
.then(user => {
if (!user) {
return res.status(401).json({
message: 'Authentication failed'
});
}
fetchedUser = user;
return bcrypt.compare(req.body.password, user.password);
})
.then(passwordMatch => {
if (!passwordMatch) {
return res.status(401).json({
message: 'Authentication failed'
});
}
const token = jwt.sign(
{ username: fetchedUser.username, userId: fetchedUser._id },
'secret_sauce',
{ expiresIn: '30d' }
);
res.status(200).json({
token: token,
userId: fetchedUser._id
});
})
.catch(err => {
return res.status(401).json({
message: 'Error occurred during authentication',
error: err
});
});
}
In addition, take a look at this screencap of the issue: https://i.sstatic.net/s6wyS.png