我正在尝试通过生成 4 个随机 8 位数字来复制 google 的备份代码系统。
for(let i = 0; i < 4; i++) {
let backendCode = Math.floor(Math.random() * (99999999 - 10000000 + 1) + 10000000);
backendCodes.push(backendCode);
}
使用后端服务发布到后端。
constructor(private http: HttpClient) { }
signUpUser(email: string, password: string, backendCodes: number[]) {
const url = "http://localhost:3000/signup/api"
const body = { email, password, backendCodes };
console.log(body); // Add this line to log the request body
const headers = new HttpHeaders({
'Content-Type': 'application/json'
});
this.http.post(url, body, { headers }).subscribe({
next: value => console.log(value),
error: error => console.log(error),
complete: () => console.log("Complete")
});
}
然后将其保存到数据库(MongoDB)中。
app.post("/signup/api", async (req, res) => {
const { email, password, backupCodes } = req.body;
console.log(req.body);
try {
const newUser = new User({
email: email,
password: password,
backupCodes: backupCodes,
});
await newUser.save();
console.log("Successful");
res.status(200).json({ message: "User signed up successfully" });
} catch (err) {
console.log("Error: ", err);
res.status(500).json({ error: "Internal Server Error" });
}
});
我尝试在发布到后端之前以及将数据保存到数据库之前记录输出
前端
signUpUser(email: string, password: string, backendCodes: number[]) {
const url = "http://localhost:3000/signup/api"
const body = { email, password, backendCodes };
console.log(body); // Test before post
const headers = new HttpHeaders({
'Content-Type': 'application/json'
});
this.http.post(url, body, { headers }).subscribe({
next: value => console.log(value),
error: error => console.log(error),
complete: () => console.log("Complete")
});
}
后端
app.post("/signup/api", async (req, res) => {
const { email, password, backupCodes } = req.body;
console.log(req.body); // Test before saving to Database
try {
const newUser = new User({
email: email,
password: password,
backupCodes: backupCodes,
});
await newUser.save();
console.log("Successful");
res.status(200).json({ message: "User signed up successfully" });
} catch (err) {
console.log("Error: ", err);
res.status(500).json({ error: "Internal Server Error" });
}
});
这是结果截图:-
这是我的架构,如果这是问题:
const userSchema = new mongoose.Schema({
email: String,
password: String,
backupCodes: [Number],
});
客户端和后端日志中显示的数组属性在您的架构中名为 backupCodes,但控制台日志显示属性名称为 backendCodes。