我尝试使用以下 JSON 正文将 POST 请求从 Postman 发送到 Firebase Firestore 数据库:
{
"name": "John Doe",
"email": "[email protected]",
"phone": "1234567890",
"password": "yourpassword"
}
但是,我的 Node.js 处理程序代码遇到了问题。这是我的代码的相关部分:
const {
createUserWithEmailAndPassword,
getAuth,
signInWithEmailAndPassword,
signOut,
updateEmail,
updatePassword,
sendPasswordResetEmail
} = require("firebase/auth");
const {
doc,
setDoc,
getDocs,
getDoc,
updateDoc,
serverTimestamp,
collection
} = require('firebase/firestore');
const {
getDownloadURL,
ref,
uploadBytes
} = require('firebase/storage');
const { db, auth } = require("../database/db-config.js");
const registration = async(req, res) =>{
const {name, email, phone, password} = req.body;
try{
const accountCredentials = await createUserWithEmailAndPassword(auth, email, password);
const user = accountCredentials.user;
const userDoc = doc(db, 'users', user.uid);
await setDoc(userDoc, {
name,
email,
phone,
uid:user.uid,
imgUrl : '',
profilePicture : '',
});
res.status(200).json({success:true, msg:'Account successfully registered'});
}catch(error){
console.log('Sign up error:', error);
if (error.code === 'auth/email-already-in-use') {
res.status(400).json({success:false, msg:'Email is already in use'});
}
}
}
module.exports = {
registration
};
但是,我收到以下错误消息:
[FirebaseError: Function setDoc() called with invalid data. Unsupported field value: undefined (found in field name in document users/eTrWurjJaVZPYN4FC6dtWq1XXqO2)] {
code: 'invalid-argument',
customData: undefined,
toString: [Function (anonymous)]
}
有趣的是,如果我使用如下硬编码值预定义 setDoc 方法,则 POST 请求会成功:
await setDoc(userDoc, {
name: 'test',
email: 'test',
phone: 'test',
uid:user.uid,
imgUrl : '',
profilePicture : '',
});
但是如果里面的数据没有预定义的话就会失败。我该如何解决这个问题?
我已经修正了错误。结果我忘记在邮递员中将原始正文类型设置为 JSON。这就是为什么 setDoc() 之前无法识别 req.body 的原因。