During development I've been using this mongodb code block to connect to database and it's been working flawlessly, but not when I deploy to Azure.
mongoose
.connect(
"mongodb://" +
process.env.COSMOSDB_HOST +
":" +
process.env.COSMOSDB_PORT +
"/" +
process.env.COSMOSDB_DBNAME +
"?ssl=true&replicaSet=globaldb",
{
auth: {
user: process.env.COSMOSDB_USER,
password: process.env.COSMOSDB_PASSWORD
}
}
)
.then(() => console.log("Connection to CosmosDB successful"))
.catch(err => console.error(err));
I was having trouble getting it to connect when deploying my app to azure so I was given a different mongodb code block to use from azure support
var mongoDBurl = process.env.MONGODB_CONNECTION;
mongoose.connect(mongoDBurl, { useNewUrlParser: true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', (callback) => {
console.log('MongoDB connectted!!');
});
, but when I use this mongodb code instead of the original, then I get Cannot set headers after they are sent to the client when trying to login to my app. Why is that?
login api
router.post("/login", (req, res, next) => {
let fetchedUser;
let username;
User.findOne({ email: req.body.email })
.then(user => {
if (!user) {
return res.status(401).json({
message: "Auth failed"
});
}
fetchedUser = user;
username= user.username;
return bcrypt.compare(req.body.password, user.password);
})
.then(result => {
if (!result) {
return res.status(401).json({
message: "Auth failed"
});
}
const token = jwt.sign(
{
email: fetchedUser.email,
userId: fetchedUser._id,
username: username
},
"secret_this_should_be_longer",
{ expiresIn: "1h" }
);
res.status(200).json({
token: token,
expiresIn: 3600,
userId: fetchedUser._id,
username: username
});
})
.catch(err => {
return res.status(401).json({
message: "Auth failed"
});
});
});