Home > Blockchain >  Firebase - ⚠ Error: Route.post() requires a callback function but got a [object Undefined]
Firebase - ⚠ Error: Route.post() requires a callback function but got a [object Undefined]

Time:01-24

So I am running into an issue while working my way through a Firebase / React tutorial and I just made it through the refactoring section which starts here: https://www.youtube.com/watch?v=m_u6P5k0vP0&t=5590s

Everything has gone well except my post function for posting one new Twitter-style update. and the error when trying to run firebase server I am getting is:

⚠  Error: Route.post() requires a callback function but got a [object Undefined]
    at Route.<computed> [as post] (/Users/tmac/Programing/HolbertonFinal/MentorMatchingApp/firebase-fuctions/functions/node_modules/express/lib/router/route.js:202:15)
    at Function.app.<computed> [as post] (/Users/tmac/Programing/HolbertonFinal/MentorMatchingApp/firebase-fuctions/functions/node_modules/express/lib/application.js:482:19)
    at Object.<anonymous> (/Users/tmac/Programing/HolbertonFinal/MentorMatchingApp/firebase-fuctions/functions/index.js:10:5)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at initializeRuntime (/Users/tmac/.nvm/versions/node/v17.3.0/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:655:29)
⚠  We were unable to load your functions code. (see above)

I'll try to get the relevant modules here but let me know if I am missing something and I can add it. I am very new to this and really appreciate all the help!

index.js

const functions = require("firebase-functions");
const app = require('express')();

const { postOneScream } = require('./handlers/screams'); // Not Working
const { signup, login } = require('./handlers/users');
const { FBAuth } = require('./util/fbAuth');


// Scream routes - Testing post functionality for social media feed posts
app.post('/screams', FBAuth, postOneScream); // Error: Route.post() requires a callback function but got a [object Undefined]

// Signup route
app.post("/signup", signup);

// Sign In route
app.post('/login', login);

// export api allows us to use express for our function formating
exports.api = functions.https.onRequest(app);

fbAuth.js

const { admin } = require('./admin');

// Check if user has a token for being logged in
module.exports = (req, res, next) => {
    let idToken;
    if(req.headers.authorization && req.headers.authorization.startsWith('Bearer ')){
      idToken = req.headers.authorization.split('Bearer ')[1];
    } else {
      console.error('No token found');
      return res.status(403).json({error: 'Unauthorized'});
    }
  
    admin.auth().verifyIdToken(idToken)
    .then(decodedToken => {
      req.user = decodedToken;
      console.log(decodedToken);
      return db.collection('users')
      .where('userId', '==', req.user.uid)
      .limit(1)
      .get();
    })
    .then(data => {
      req.user.handle = data.docs[0].data().handle;
      return next();
    })
    .catch((err) => {
      console.error('Error while verifying token', err);
      return res.status(403).json({err})
    })
}

screams.js

const { db } = require('../util/admin');

exports.postOneScream = (req, res) => {

    const newScream = {
        body: req.body.body,
        userHandle: req.user.handle,
        createdAt: new Date().toISOString()
    };

    db.collection('screams').add(newScream).then((doc) => {
        res.json({ message: `document ${doc.id} created successfully` })
    })
    .catch((err) => {
        res.status(500).json({ error: 'something went wrong' });
        console.error(err);
    })
};

Thanks again for any and all help, I am really trying to learn webdev but boy there is a lot and each step only shows me more how much I don't know :)

CodePudding user response:

So, in index.js, you are importing "FBAuth" from "./util/fbAuth",

const { FBAuth } = require("./util/fbAuth");

but in './util/fbAuth', you are not exporting "FBAuth".

Modify your fbAuth file to something like this,

const { admin } = require('./admin');

// Check if user has a token for being logged in
module.exports.fbAuth = (req, res, next) => {
    let idToken;
    if(req.headers.authorization && req.headers.authorization.startsWith('Bearer ')){
      idToken = req.headers.authorization.split('Bearer ')[1];
    } else {
      console.error('No token found');
      return res.status(403).json({error: 'Unauthorized'});
    }
  
    admin.auth().verifyIdToken(idToken)
    .then(decodedToken => {
      req.user = decodedToken;
      console.log(decodedToken);
      return db.collection('users')
      .where('userId', '==', req.user.uid)
      .limit(1)
      .get();
    })
    .then(data => {
      req.user.handle = data.docs[0].data().handle;
      return next();
    })
    .catch((err) => {
      console.error('Error while verifying token', err);
      return res.status(403).json({err})
    })
}
  •  Tags:  
  • Related