问题描述
这是在我的app.js中,我在其中导入Firebase并将其初始化
const firebase = require('firebase');
firebase.initializeApp({
apiKey: ************,authDomain: ****************,databaseURL: **********",projectId: ********,storageBucket: ***********,messagingSenderId: **********,appId: *********,measurementId: *********
});
app.use( (req,res,next) => {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
req.session.isLoggedIn = true;
} else {
req.session.isLoggedIn = false;
}
});
res.locals.isAuthed = req.session.isLoggedIn;
res.locals.csrftoken = req.csrftoken();
next();
});
但是在导入Firebase之后的auth.js控制器中,它将无法正常工作
const firebase = require('firebase');
exports.postSignup = (req,next) => {
const name = req.body.name;
const email = req.body.email;
const password = req.body.password;
const confirmPassword = req.body.password;
if(password === confirmPassword){
firebase.auth().createuserWithEmailAndPassword(email,password)
.then(function(firebaseUser) {
const user = new User({
name: name,email: email,cart: {items: []}
});
return user.save();
})
.then(result => {
res.redirect('/login');
})
.catch(error => {
if (error.code == 'auth/email-already-in-use') {
//'auth/wrong-password'
req.flash('error','Already Registered');
return res.redirect('/signup');
}
});
}
发生此错误 TypeError:firebase.auth.createuserWithEmailAndPassword不是一个函数 在exports.postSignup(/ media / rishav / Project Space / Projects / Web Development / Node Express / Controllers / auth.js:95:23)
const firebase = require('firebase-admin');
// Fetch the service account key JSON file contents
const serviceAccount = require("../Data/firebase-service-account.json");
// Initialize the app with a service account,granting admin privileges
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),databaseURL: "****",databaseAuthVariableOverride: null
});
解决方法
您可能想说:
firebase.auth().createUserWithEmailAndPassword(...)
在“ auth”之后注意括号。
但是更大的问题是,您不应该在nodejs应用程序中使用Firebase Web客户端库。相反,您应该使用Firebase Admin SDK,这是一个完全不同的模块,并以服务帐户初始化的管理员权限运行。您可以在后端代码中将其用于create user accounts。