我只是 Javascript 和 MERN 的初學者。我正在嘗試創建一個小型社交媒體應用程式,并且在我的注冊 api 中,我給出了用戶資訊的回應。我無法隔離和隱藏密碼。
這是代碼
userRouter.post("/signUp", async (req, res) => {
const {name, userName, email, password} = req.body
const existingUser = await userSchema.findOne({email: email})
const SameUserName = await userSchema.findOne({userName: userName})
if (existingUser) {
return res.status(406).send({
message: `sorry, an account with email: ${email} has already been created.`
})
} else if (SameUserName) {
return res.status(406).send({
message: `sorry, user name taken. Try another one...`
})
}
const newUser = new userSchema({
name,
userName,
email,
password
})
console.log(newUser)
try {
await newUser.save()
res.status(201).send({
message: `Account successfully created!`,
user: newUser
})
} catch (err) {
res.send({
message:`Something went wrong`,
})
}
})
那么,如何在沒有密碼的情況下發送用戶資訊?
uj5u.com熱心網友回復:
跟進我在下面留下的評論,這就是你可以做的。
你必須重構你的代碼。
try {
const userSaved = await newUser.save();
delete userSaved.password // assuming this is the property name
return res.status(201).send({ message: 'Account created successfully', user: userSaved })
}
你也可以:
try {
const userSaved = await newUser.save();
delete userSaved.password // assuming this is the property name
return userSaved;
}
在這種情況下,您在前端處理訊息和所有內容。
uj5u.com熱心網友回復:
您需要在架構上實作toJSON和transform方法。這將允許您在創建模式物件以及將它們序列化并發送到客戶端時“攔截”它們。
這是一個例子:
架構:
import { Schema, model } from 'mongoose';
const schema = new Schema(
{
name: {
required: true,
type: String
},
userName: {
required: true,
type: String
},
email: {
required: true,
type: String
},
password: {
required: true,
type: String
}
},
{
// here, we implement the `toJSON` method to serialize the user object sans password, __v;
// we'll also convert the mongo-specific `_id` property to a db-agnostic format
toJSON: {
transform(_, ret) {
ret.id = ret._id;
delete ret.password;
delete ret._id;
delete ret.__v;
}
}
}
);
// this is our user schema, used to initialize new user objects before we persist them in the db
const User = model('User', schema);
userRouter.post('/signUp', async (req, res) => {
// grab the inputs - we do *not* at this time know whether any of these are valid - they must be validated
const { name, userName, email, password } = req.body;
// validate the email format, performing checks for any requirements you wish to enforce
if (!email) {
// error response
}
// now, we check if the email is already in-use
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).send({
message: `sorry, an account with email: ${email} has already been created.`
});
}
// validate userName format here
if (!userName) {
// error response
}
// notice we don't bother making this query until `existingUser` check has passed
// this way we don't incur needless computation
const sameUserName = await User.findOne({ userName });
if (sameUserName) {
return res.status(400).send({
message: `sorry, user name taken. Try another one...`
});
}
// validate name and password and handle accordingly here
if (!name || ...) {
// error response
}
// assuming all is well, we create a new user with the schema
// think of the schema as a template
const newUser = new User({ name, userName, email, password });
// save the new user
await newUser.save().catch((ex) => {
// error response
});
res.status(201).send({
message: `Account successfully created!`,
user: newUser
});
});
您還可以查看express-validator,這是一個為您處理大部分請求正文驗證的中間件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/409212.html
標籤:
上一篇:表示接收字串而不是布林值
