【问题标题】:how to hide my client's password in API response如何在 API 响应中隐藏我的客户密码
【发布时间】:2022-01-10 16:40:47
【问题描述】:

我只是 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`,
        })
    }
})

那么,如何在没有密码的情况下发送用户信息?

【问题讨论】:

标签: javascript express


【解决方案1】:

根据我在下面留下的评论,您可以执行以下操作。

你必须重构你的代码

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;
}

在这种情况下,您在前端处理消息和所有内容。

【讨论】:

  • 好的,谢谢老兄!
  • 我的第一篇文章....从现在开始我会重构,对不起
  • 太棒了!还有一件事,您不需要执行数据库上的请求。在请求的开头,您使用电子邮件执行 findOne,使用用户名执行另一个。在您的实体上,您可以将 @Unique 装饰器添加到它。这将确保某个值始终是唯一的。哦!不要忘记点击回复中的“检查”图标 :) 一切顺利!
  • 刚刚实施了你的建议......再次Tnx
【解决方案2】:

您需要在架构上实现 toJSONtransform 方法。这将允许您在创建模式对象以及将它们序列化并发送到客户端时“拦截”它们。

这是一个例子:

架构:

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,这是一个为您处理大部分请求正文验证的中间件。

【讨论】:

  • 顺便说一句,406 状态码在这里不合适;当服务器无法使用请求中指定的接受标头进行响应时,应使用它。使用 400。
  • 谢谢你,Bruh,你为我制作了一个完整的教程!将通过验证。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 2016-11-09
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
相关资源
最近更新 更多