MongoDB not connecting to database in azure - javascript

im trying to connect my express application to mongoDB and it works fine when I host the express application locally however when I upload it to Azure App Service it crashes.
What I've tried so far -
-Replacing the connection string with an environmental variable
-Removing the connection code entirely to identify exactly where the error occurs
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const mongoose = require('mongoose')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const workoutRoutes = require('./routes/workouts')
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//Connect to mongoose server
//------------------------------------------------- ERROR CAUSED BY THIS BLOCK OF CONNECTION CODE
mongoose.connect(process.env.MONGO_URI).then(() => {
console.log('Connected to the mongo databse database');
}).catch((err) => {
console.log(err)
})
//------------------------------------------------- ERROR CAUSED BY THIS BLOCK OF CONNECTION CODE
app.use('/', indexRouter);
app.use('/users', usersRouter);
//app.use('/api/workouts', workoutRoutes)
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Application settings in azure

Okay, so I've managed to work out the issue. It's with the mongoose version. I was using v6 so I downgraded to v5.11.10 and it worked perfectly. I don't know the exact part of mongoose v6 that is causing the issue but I've found a workaround for now.

Related

Root not working for admin pannel in node js

I am tring to give 2 roots one for admin and other for user.
To access the admin pannel http://localhost:3000/admin
To access to user page http://localhost:3000.
But the problem is when an option is selected from the menu of admin pannel it will not take to that page , and shows a 404 error.[if i click option which have an href add-faq it must show like http://localhost:3000/admin/add-faq. but it is showing http://localhost:3000/add-faq and giving 404 error]
But the user page had no problems.
I am using node js,Express,Hbs.
All files are named properly and no files missing..
If the http://localhost:3000/admin/add-faq is manually given the stylesheets are not loading (404)
GITHUB :https://github.com/bimalboby/clevercode
PLEASE HELP AND THANKS IN ADVANCE😊
My App.js file:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var userRouter = require('./routes/user');
var adminRouter = require('./routes/admin');
var hbs = require('express-handlebars')
var app = express();
var db=require('./config/connection')
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.engine('hbs',hbs({extname:'hbs',defaultLayout:'layout',layoutDir:__dirname+'/views/layouts',partialsDir:__dirname+'/views/partials'}))
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
db.connect((err)=>{
if(err) console.log('connection failed'+err);
else console.log('connected to database');
})
app.use('/', userRouter);
app.use('/admin',adminRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;```
**My admin.js:**
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.render('adminintro',{admin:true})
});
router.get('/add-prices', (req,res)=>{
res.render('faqadmin',{admin:true})
});
router.get('/add-faq',(req,res)=>{
res.render('faqadmin',{admin:true})
})
module.exports = router;
**my user.js:**
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index',{admin:false,indexpage:true});
});
router.get('/faq',(req,res)=>{
res.render('faq',{indexpage:true})
});
router.get('/web-design-pricing',(req,res)=>{
res.render('price',{indexpage:true})
});
router.get('/e-commerce-pricing',(req,res)=>{
res.render('price',{indexpage:true})
});
router.get('/seo-pricing',(req,res)=>{
res.render('price',{indexpage:true})
});
module.exports = router;
Try adding the complete end point like below in /views/partials/admin-header.hbs file like below,
<li>FAQ</li>
Your user routes are with the endpoint '/' in server.js.So its working,where as admin need to be linked like /admin/add-faq

Deploying app to Heroku, ENV variables not wokring

I have recently deployed my node js app to Heroku and am having some trouble getting my app to work. My app loads but when i try to sign in it breaks. As far as I can tell is the environment variable are not loading correctly for some reason. The db variable is a string taken from my .ENV file and is the Monogo URI used to connect to mongo db. For some reason when heroku runs it process.env.MongoURI is coming undefined. Does anybody know why this might be happening?
The specific error I am getting is.
Error
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
App.js
/* eslint-disable no-unused-vars */
/* eslint-disable comma-dangle */
/* eslint-disable no-console */
/* eslint-disable arrow-parens */
const createError = require('http-errors');
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const dotenv = require('dotenv');
dotenv.config();
const indexRouter = require('./server/index');
const port = process.env.PORT || 3000;
const app = express();
require('./server/config/passport')(passport);
// DB Config
const db = process.env.MongoURI;
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true }) // I beleieve this is the line that is breaking the code.
.then(() => { console.log('MONGODB Connected'); })
.catch(err => console.log(err));
app.use(expressLayouts);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404));
});
// error handler
app.use((err, req, res, next) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(port, () => {
console.log(`Running on port ${port}`);
});
module.exports = app;
You probably should use Heroku's built in environment variable editor for this purpose.
First of all, make sure that your .env is added to your .gitignore file. When you deploy your project to heroku, it will automatically adapt to the variables on its new host.
Find more: https://devcenter.heroku.com/articles/node-best-practices#be-environmentally-aware

File Upload returning "undefined"

So I am using Express File Upload and when I attempt to send a post request to it, it returns the error from the error-handler that is set up, which essentially it couldn't find any files when I console.log(req.files) it returns undefined, which is why the error is being sent back, but I don't know how to fix the problem.
Index.js
router.post('/upload-avatar', async (req, res) => {
try {
console.log(req.files)
if(!req.files) {
res.send({
status: false,
message: 'No file uploaded'
});
} else {
//Use the name of the input field (i.e. "avatar") to retrieve the uploaded file
let avatar = req.files.avatar;
//Use the mv() method to place the file in upload directory (i.e. "uploads")
avatar.mv('./uploads/' + avatar.name);
//send response
res.send({
status: true,
message: 'File is uploaded',
data: {
name: avatar.name,
mimetype: avatar.mimetype,
size: avatar.size
}
});
}
} catch (err) {
res.status(500).send(err);
}
});
App.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const fileUpload = require('express-fileupload');
const cors = require('cors');
const bodyParser = require('body-parser');
const _ = require('lodash');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
app.use(fileUpload({
createParentPath: true
}));
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I am using an azure server, and at the moment I am using postman to get it working first!
Thanks In Advance!
Middlewares should be ordered appropriately. Your file upload middleware was placed below your index router. So when a request hits the server Express would run your indexRouter’s handler before the upload middleware and unless your handler calls next(), the file upload middleware would not process your request. And you cannot call next() since it would mean “I’m done with my part, hand this request (req) to the next middleware/handler”.
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const fileUpload = require('express-fileupload');
const cors = require('cors');
const bodyParser = require('body-parser');
const _ = require('lodash');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(fileUpload({
createParentPath: true
}));
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;

How to fix an error 'Undefined and error message: this.f is not a constructor' in firebase.auth().signInWithEmailAndPassword() method?

I am using Firebase for my web app. I am using Firebase client SDK in Node.js for authentication of users in my webapp. But firebase.auth().signInWithEmailAndPassword() function is throwing error with error code:
Undefined and error message: this.f is not a constructor.
I have searched on net for these errors but couldn't find a suitable answer. I am also using express-generator in my web app.
This is my app.js file
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const firebase = require('firebase/app');
require('firebase/auth');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var loginRouter = require('./routes/login');
var app = express();
const firebaseConfig = {
Here lies the credentials
};
firebase.initializeApp(firebaseConfig);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
This is my login.js which is used in the login route
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
const firebase = require('firebase/app');
require('firebase/auth');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('login');
});
router.post('/', urlencodedParser, function(req,res){
console.log('details', req.body);
firebase.auth().signInWithEmailAndPassword(req.body.email, req.body.pass).then(function(){
res.render('dashboard', {data: req.body});
}).catch(function(error) {
// Handle Errors here.`enter code here`
var errorCode = error.code;
var errorMessage = error.message;
console.log('Error code', errorCode);
console.log('Error message', errorMessage);
});
});
module.exports = router;
login.ejs is a form, on submitting the form I get these errors
Rendered login.ejs on the browser
error code: Undefined and error message: this.f is not a constructor
Here i am getting the values from the form but auth fails
Could you please advise me on resolution?
This issue was accidentally introduced in v6.2.1. v6.2.0 should be fine. Firebase team is working on a fix to be pushed shortly.
Seems like a bug as I'm seeing it too. Reported this at https://github.com/firebase/firebase-js-sdk/issues/1906
"dependencies": {
"firebase": "^5.9.0",
"firebase-admin": "~7.0.0",
"firebase-functions": "^2.2.0"
},
The above versions are fine to use

Internal server error when using ejs with expressjs

I'm new to nodejs and I'm trying to use ejs to template my website. But when I tried to set the view engine, I keep getting the error code 500 - Internal Server Error. Here is my app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var engines = require('consolidate');
var index = require('./routes/index');
var main = require('./routes/main');
var suoimo = require('./routes/suoimo');
var vungtau = require('./routes/vungtau');
var video = require('./routes/video');
var dalat = require('./routes/dalat');
var app = express();
app.use(express.static('./'));
app.use(express.static('./public'));
// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.engine('html', engines.mustache);
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.use('/', index);
app.use('/video', video);
app.use('/', index);
app.use('/suoimo', suoimo);
app.use('/vungtau', vungtau);
app.use('/main', main);
app.use('/dalat', dalat);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
But if I set the view and view engine like this:
app.set('views', path.join(__dirname, 'views'));
app.engine('html', engines.mustache);
app.set('view engine', 'html');
Everything work fine, anyone know why? Please help
I tested your code and everything works fine. But if I uninstall ejs I get error 500 Internal server error. I think that this is your problem. Try to run npm install ejs and try again with the same configuration, it should work fine now.

Categories