user10728848
user10728848

Reputation: 133

ReferenceError: firebase is not defined - in Nodejs/express

I'm trying to test a simple app in Nodejs by connecting to the Firebase database, but I keep getting this error, although, I've initialized the cloud firebase. I also did npm i firebase What am I missing and how to fix the error?

Running the app and upon filling the form and pressing the submit button will not succeed. It prints out the following error. This is the complete error:

PS C:\Users\WorkoutApp_v1> node app.js
Warning, FIREBASE_CONFIG and GCLOUD_PROJECT environment variables are missing. Initializing firebase-admin will fail Server started on port: 3000
ReferenceError: firebase is not defined
at C:\Users\WorkoutApp_v1\routes\workouts.js:22:19
at Layer.handle [as handle_request] (C:\Users\WorkoutApp_v1\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\WorkoutApp_v1\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\WorkoutApp_v1\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\WorkoutApp_v1\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\WorkoutApp_v1\node_modules\express\lib\router\index.js:281:22 at Function.process_params (C:\Users\WorkoutApp_v1\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\WorkoutApp_v1\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\WorkoutApp_v1\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\WorkoutApp_v1\node_modules\express\lib\router\index.js:47:12)
POST /workouts/add 500 27.533 ms - 1420

This is my workout.js file

const express = require('express');
const router = express.Router();

router.get('/add', function(req,res,next) {
    res.render('workouts/add');
});

router.post('/add', function(req,res,next) {
    const workout = {
        name: req.body.Name,
        discription: req.body.Discription,
        set: req.body.Set,
        RepsTime: req.body.RepsTime
    }
    // console.log(workout);
    // return;

    const fbRef = firebase.database().ref();
    var dbRef = fbRef.child('workouts');
    dbRef.push().set(workout);

    req.flash('success_msg', 'Workout saved');
    res.redirect('/workouts');
});

module.exports = router;

This is my app.js file

const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const { check, validationResult } = require('express-validator');
const flash = require('connect-flash');

const firebase = require('firebase');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();


var firebaseConfig = {
  apiKey: "AIzaSyC9xvJUIlgoWkS0H4Z3nQ5AXKN2y_Nnt7U",
  authDomain: "workout-8g855.firebaseapp.com",
  databaseURL: "https://workout-8g855.firebaseio.com",
  projectId: "workout-8g855",
  storageBucket: "workout-8g855.appspot.com",
  messagingSenderId: "422111087011",
  appId: "1:422111087011:web:cd6252c0a00c26428a604c",
  measurementId: "G-G3L6FN0J4F"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);


// const serviceAccount = require('./serviceAccountKey');
//admin.initializeApp(functions.config().firebase);
// admin.initializeApp({
//     credential: admin.credential.cert(serviceAccount)
// });


// Route Files
const routes = require('./routes/index');
const workouts = require('./routes/workouts');

// Init App
const app = express();

// View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Logger
app.use(logger('dev'));

// Body Parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// Handle Sessions
app.use(session({
  secret:'secret',
  saveUninitialized: true,
  resave: true
}));

app.post('/user', [
  // username must be an email
  check('username').isEmail(),
  // password must be at least 5 chars long
  check('password').isLength({ min: 5 })
], (req, res) => {
  // Finds the validation errors in this request and wraps them in an object with handy functions
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() });
  }

  User.create({
    username: req.body.username,
    password: req.body.password
  }).then(user => res.json(user));
});


// Static Folder
app.use(express.static(path.join(__dirname, 'public')));

// Connect Flash
app.use(flash());

// Global Vars
app.use(function (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();
});

// Routes
app.use('/', routes);
app.use('/workouts', workouts);

// Set Port
app.set('port', (process.env.PORT || 3000));

// Run Server
app.listen(app.get('port'), function(){
  console.log('Server started on port: '+app.get('port'));
});

Upvotes: 0

Views: 3596

Answers (2)

Clément
Clément

Reputation: 83

In workout.js you use

const fbRef = firebase.database().ref();

But you never define it in this file

Upvotes: 0

Ghonima
Ghonima

Reputation: 3082

In workout.js

You need to add

const firebase = require('firebase');

as you are calling it in the following line

const fbRef = firebase.database().ref();

Upvotes: 4

Related Questions