I am trying to follow a video on youtube called "Full Stack React & Firebase Tutorial - Build a social media app" and I am having trouble with the code for adding new users to firebase..
My code looks like this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('express')();
admin.initializeApp();
const firebaseConfig = {
apiKey: "apiKey",
authDomain: "socialtutorial.firebaseapp.com",
databaseURL: "https://socialtutorial.firebaseio.com",
projectId: "socialtutorial",
storageBucket: "socialtutorial.appspot.com",
messagingSenderId: "SenderID",
appId: "1:848457683801:web:a276f7436db03ac500b248"
}
const firebase = require('firebase');
firebase.initializeApp(firebaseConfig);
app.get('/challenges', (req, res) => {
admin
.firestore()
.collection('challenges')
.orderBy('challengeCreated', 'desc')
.get()
.then(data => {
let challenges = [];
data.forEach(doc => {
challenges.push({
challengeId: doc.id,
challengeName: doc.data().challengeName,
challengeDescription: doc.data().challengeDescription,
challengeCreated: doc.data().challengeCreated
});
});
return res.json(challenges);
})
.catch (err => console.error(err));
})
app.post('/challenge', (req, res) => {
const newChallenge = {
challengeName: req.body.challengeName,
challengeDescription: req.body.challengeDescription,
challengeCreated: new Date().toISOString()
};
admin.firestore()
.collection('challenges')
.add(newChallenge)
.then(doc => {
res.json({message: `document ${doc.id} created successfully`});
})
.catch(err => {
res.status(500).json({error: 'something went wrong'});
console.error(err);
})
})
//Sign Up Route
app.post('/signup', (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
userName: req.body.userName
}
//TODO Validate
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password)
.then(data => {
return res.status(201).json({message: `user ${data.user.uid} signed up successfully`});
})
.catch(err) => {
console.error(err);
return res.status(500).json({error: err.code})
}
})
exports.api = functions.region('europe-west1').https.onRequest(app);
Now, when I try "firebase deploy" or "serve" I get an unexpected token error. The error is the "." after firebase... I must have missed something in the code above, but I can't see it for the life of me. I know this is a stupid mistake and I should be able to fix it on my own, but I literally can't see, where the error comes from...
Any help from you guys? Thanks a lot in advance!
I'm not sure if maybe you copied pasted to the question incorrectly from your editor but the only thing I see is the last catch of your code. It seems you never pass a callback to it.
you defined it as follows
.catch(err) => {
but it should be
.catch(err => {
Related
her i build my firebase and initialize it and finally was able to get the data from it but the problem was i couldnt use express.get() and json the data into the server im not sure what is the problem
let initializeApp = require("firebase/app");
let getAnalytics = require("firebase/analytics");
let firestore = require("firebase/firestore");
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
};
const app = initializeApp.initializeApp(firebaseConfig);
const db = firestore.getFirestore();
const colRef = firestore.collection(db, "products");
async function getData() {
const querySnap = await firestore.getDocs(colRef);
var product = [];
querySnap.forEach((pr) => {
console.log(pr.data());
});
}
const express = require("express");
const ex = express();
let data = getData().then(
ex.get("/store", (req, res) => {
res.json(data);
ex.listen(5000, () => {
console.log(data);
})
})
);
i tried the code above nothing worked and got this error:
debug('dispatching %s %s', req.method, req.url);
^
TypeError: Cannot read properties of undefined (reading 'method')
at Function.handle (C:\Users\hamdan\OneDrive\Desktop\hello\node_modules\express\lib\router\index.js:139:34)
at Function.handle (C:\Users\hamdan\OneDrive\Desktop\hello\node_modules\express\lib\application.js:181:10)
at app (C:\Users\hamdan\OneDrive\Desktop\hello\node_modules\express\lib\express.js:39:9)
i tired this
let data = getData().then(() => {
ex.get("/store", (req, res) => {
res.json(data);
});
ex.listen(5000, () => {
console.log(data);
});
});
it didnt give back an error but the problem is the data styed empty
you should put your server.listen in a different scope, not inside a get request scope. Your server should start before everything.
ex.get("/store", (req, res) => {
try{
res.json(data);
}catch(error){
console.log(error)
}})
ex.listen(5000, () => {
console.log(data);
})
`
Try this
ex.get("/store", async(req, res) => {
try{
let data = await get.Data()
console.log(data); //to see what you are recieving
res.json(data);
}catch(error){
console.log(error)
}})
ex.listen(5000, () => {
console.log("server running on port 5000);
})
I am trying to access the user with _id in node js and mongodb. I have successfully connected to the database and i am using the same user id as in mongodb compass but it is giving me null in my console. Any help in the matter?
regards
const mongodb = require('mongodb');
const getDb = require('../util/database').getDb;
const ObjectId = mongodb.ObjectId;
static findById(userId) {
const db = getDb();
return db
.collection('users').findOne({ _id: new ObjectId(userId) }).then(user => {
return user;
})
.catch(err => {
console.log(err);
});
}
}
Here is the app.js
app.use((req, res, next) => {
User.findById('637135a7bf28b66e21340c2f').then(user => {
req.user = user
console.log(user)
next();
})
.catch(err => console.log(err));
});
mongoConnect(() => {
app.listen(3000);
});
Same as Title says, Why does my Get request sometimes work, but most of the time it 404's?
Been messing around with taking the "next()" out, but it doesnt matter same effect. Same with making the "res.json(req.user.firstName);" in the -----router.get("/user, auth, (req,res){})-----
module.exports.isAuth = (req, res, next) => {
if (req.isAuthenticated()) {
console.log(req.user);
res.json(req.user.firstName);
//next()
} else {
console.log("Nope");
res
.status(401)
.json({ msg: "You are not authorized to view this resource" });
}
};
when the get request DOES work, the log on the backend here ^^^^ gets logged twice, in 2 different ways like bwloe. nice/pretty and ugly.
{
_id: 60e9fad2837ff62fcb580f27,
username: 'drakecoleman#rocketmail.com',
firstName: 'Drake',
lastName: 'Coleman',
hash: 'e017095b5684f72d88d9103f3a5df9dfbcb8fe23e823b6f0551a20151710721304b58cb02bc62b60098a383d0f573fdf5bcd30aa89a5b266db0d7aceb6d25656',
salt: '7e040e90411d647200cc9cc120a1b3b182b035105ce3488fbcbfd39b56f44d9b',
admin: true,
__v: 0
}
{"_id":"60e9fad2837ff62fcb580f27","username":"drakecoleman#rocketmail.com","firstName":"Drake","lastName":"Coleman","hash":"e017095b5684f72d88d9103f3a5df9dfbcb8fe23e823b6f0551a20151710721304b58cb02bc62b60098a383d0f573fdf5bcd30aa89a5b266db0d7aceb6d25656","salt":"7e040e90411d647200cc9cc120a1b3b182b035105ce3488fbcbfd39b56f44d9b","admin":true,"__v":0}
When it 404's, the log only logs the ugly version of the user on the backend.
index.js
const router = require("express").Router();
const passport = require("passport");
const bodyParser = require("body-parser");
const genPassword = require("../lib/passwordUtils").genPassword;
const connection = require("../config/database");
const mongoose = require("mongoose");
const User = mongoose.models.User;
const isAuth = require("./authMiddleware").isAuth;
router.use(bodyParser.urlencoded({ extended: false }));
/**
* -------------- GET ROUTES ----------------
*
*/
router.get("/user", isAuth);
React Front End
user.js
import React from "react";
// import { Redirect } from "react-router-dom";
function UserProfile() {
// if (props.auth === true) {
// return <Redirect to="/login" />;
// } else {
// return <h1 className="red">Logged in </h1>;
// }
fetch("http://localhost:3000/user", {
method: "GET",
credentials: "include",
withCredentials: true,
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.log(err));
return <h1>Hello</h1>;
}
export default UserProfile;
This is in the console on the front end before the request, but i dont think its an issue since i get this on other routes with no issue "[HMR] Waiting for update signal from WDS..."
but I do get this error first on the front end console when it 404's
user.js:10 GET http://localhost:3000/user 404 (Not Found)
then after a few seconds I get (its also not typed in red background either, just white text)
TypeError: Failed to fetch
user.js:10 Fetch failed loading: GET "http://localhost:3000/user".
Someone on the discord says to make sure I have the sessions initliazed and I do, on the app.js backend page.
app.use(passport.initialize());
app.use(passport.session());
Just found out the issue. Just goes to show you can never go wrong in showing all of your code. It ended up being my deSerialize user middleware. It was set up as
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, JSON.stringify(user));
})
.then((user) => {
done(null, user);
})
.catch((err) => done(err));
});```
And when I changed to to this, my site worked 100%.
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
})
.then((user) => {
done(null, user);
})
.catch((err) => done(err));
});
Forgive me to the people who helped who wasn't aware of this part of the code.
I am using ReactJS with Firebase to make functions. My motive is to create a user signup function. Following is the code for it.
app.post( '/signup', (req, res)=> {
const newUser = {
email : req.body.email,
password : req.body.password,
confirmPassword : req.body.confirmPassword,
handle : req.body.handle,
};
firebase.auth().createUserWithEmailAndPassword('newUser.email', 'newUser.password')
.then((data)=>{
return res.json({message: `user signed up successfully`});
} ).catch( (err) => { console.error(err); return res.json({error : err.code}) } );
} )
It also requires the use of Firebase initialization with proper credentials. The code i am including below :
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('express')();
const firebase = require('firebase');
const firebaseConfigg = {
apiKey: "A*************************s",
authDomain: "socialape-9ede9.firebaseapp.com",
databaseURL: "https://socialape-9ede9.firebaseio.com",
projectId: "socialape-9ede9",
storageBucket: "socialape-9ede9.appspot.com",
messagingSenderId: "105*****9789",
appId: "1:1054747689789:web:075f037f03b59627edfb54",
measurementId: "G-ZY1LNR052N"
};
admin.initializeApp();
firebase.initializeApp(firebaseConfigg);
The firebase functions log is showing this error when i try to run firebase deploy :
How to get through this error? I have been following this youtube tutorial link :Youtube social networking website tutorial with react and firebase and around 42.55min the guy uses firebase authentication, and copies a code in project settings, which seems to be different for me (obvioously i am not expecting the same api keys etc, but the format, it actually asks me to add a web app, but not in the tutorial) when i go through the exact same steps, snippet for me looks like the const firebaseconfig that i gave in the code snippet above.
My VS Code says:
Error: Functions did not deploy properly.
In a Cloud Function, you need to use the Admin SDK if you want to interact with one of the Firebase services (Auth, Firestore, Cloud storage, etc.).
So, you need to adapt you code as follows:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('express')();
admin.initializeApp();
//...
app.post( '/signup', (req, res)=> {
const newUser = {
email : req.body.email,
password : req.body.password,
// see https://firebase.google.com/docs/reference/admin/node/admin.auth.UserRecord
};
admin.auth().createUser(newUser)
.then((data)=> {
return res.send({message: `user signed up successfully`});
})
.catch((err) => {
console.error(err);
return res.status(500).send({error : err.code}) });
});
See also https://firebase.google.com/docs/auth/admin/manage-users?authuser=0#create_a_user.
My code: Inside of an index.js file. Set up using firebase init command, functions selected. I'm able to deploy without error if I comment out the code:
const firebase = require("firebase");
firebase.initializeApp(config);
It throws the error if I leave this in. I've tried running npm install and npm rebuild in both the functions folder and the parent folder.
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const app = require("express")();
admin.initializeApp();
const config = {
apiKey: "apiKey",
authDomain: "socialapp.firebaseapp.com",
databaseURL: "https://socialapp.firebaseio.com"
storageBucket: "socialapp.appspot.com"
};
const firebase = require("firebase");
firebase.initializeApp(config);
app.get("/screams", (req, res) => {
admin
.firestore()
.collection("screams")
.orderBy("createdAt", "descending")
.get()
.then(data => {
let screams = [];
data.forEach(doc => {
screams.push({
screamId: doc.id,
body: doc.data().body,
userHandle: doc.data().userHandle,
createdAt: doc.data().createdAt
});
});
return res.json(screams);
})
.catch(err => console.log(err));
});
app.post("/scream", (req, res) => {
const newScream = {
body: req.body.body,
userHandle: req.body.userHandle,
createdAt: new Date().toISOString()
};
admin
.firestore()
.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);
});
});
//Signup Route
app.post("/signup", (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
handle: req.body.handle
};
//Todo validate data
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password)
.then(data => {
return res
.status(201)
.json({ message: `user ${data.user.uid} signed up successfully` });
})
.catch(err => {
console.err(error);
return res.status(500).json({ error: err.code });
});
});
exports.api = functions.https.onRequest(app);
Error from console:
i deploying functions
i functions: ensuring necessary APIs are enabled...
+ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
Error: Error parsing triggers: The gRPC binary module was not installed. This may be fixed by running "npm rebuild"
Original error: Cannot find module 'C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\src\node\extension_binary\node-v79-win32-x64-unknown\grpc_node.node'
Require stack:
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\src\grpc_extension.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\src\client_interceptors.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\src\client.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\grpc\index.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\#firebase\firestore\dist\index.node.cjs.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\node_modules\firebase\dist\index.node.cjs.js
- C:\Users\alex_\Desktop\socialapp-functions\functions\index.js
- C:\Users\alex_\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js
Try running "npm install" in your functions directory before deploying.
Having trouble? Try firebase [command] --help
You don't need the "firebase" module here (it's mostly meant for web application, note nodejs apps). You can use the Admin SDK instead to create a user account as described in the documentation.