我们如何在node.js中使用Firebase Auth创build用户?

我正在尝试在nodejs中使用Firebase身份validation创build用户帐户。 它不起作用,我不知道为什么。 这里是代码和nodejs产生的错误:

var config = {.......}; // i can't share the config var app = firebase.initializeApp(config); var db = app.database(); var auth = app.auth(); auth.createUserWithUsernameAndPassword("anemail@gmail.com", "@NewPassWord").then( function(user){ console.log(user);}, function(error){ console.error(error);} ); 

由NodeJS生成错误:

 TypeError: Object [object Object] has no method 'createUserWithUsernameAndPassword' at Object.<anonymous> (/home/antonio/Projects/firebase/app.js:20:6) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:906:3 

好吧,我不认为"createUserWithUsernameAndPassword"方法的作品,

使用这个而不是createUserWithEmailAndPassword

您在Firebase使用电子邮件时使用了用户名

截至2017年5月,这是我们正在使用的成功。

  // Create the authenticated user admin.auth().createUser({ email: email, password: password, displayName: `${firstName} ${lastName}`, }) 

我终于在Node.js中工作了 您的app是否是firebase-admin的实例,而不是firebase

在我的express应用程序中,我初始化了主要的app.js中的app.js就像这样(相当标准的票价):

 var firebase = require("firebase"); firebase.initializeApp ({ apiKey: "xxx", authDomain: "xxx", databaseURL: "xxx", storageBucket: "xxx", messagingSenderId: "xxx" }); 

然后在负责创build用户的route ,我这样做:

 var firebase = require("firebase"); router.post('/register', function(req, res, next) { var email = req.body.email; var password = req.body.password; firebase.auth().createUserWithEmailAndPassword ( email, password ) .then(function(userRecord) { res.location('/user/' + userRecord.uid); res.status(201).end(); }) .catch(function(error) { res.write ({ code: error.code }); res.status(401).end(); }); }); 

赛勒斯的回答是正确的。

不过请注意,截至2016年11月,要做到这一点的方法如下:

 firebaseAdmin.auth().createUser({ email: "user@example.com", password: "secretPassword" }) .then(function(userRecord) { // A UserRecord representation of the newly created user is returned console.log("Successfully created new user:", userRecord.uid); }) .catch(function(error) { console.log("Error creating new user:", error); }); 

在官方文档中查看更完整的指南。