Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
cómo ocultar la contraseña de mi cliente en la respuesta de la API

Solo soy un principiante en Javascript y MERN. Estoy tratando de crear una pequeña aplicación de redes sociales, y en mi API de registro, di una respuesta de la información del usuario. No podía segregar y ocultar la contraseña.

aquí está el código

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

Entonces, ¿cómo puedo enviar la información de usuario sin la contraseña?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Deberá implementar los métodos toJSON y transform en su esquema. Esto le permitirá 'interceptar' los objetos de esquema a medida que se crean y se serializan y envían al cliente.

Aquí hay un ejemplo:

Esquema:

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

También puede consultar express-validator , un middleware que maneja gran parte de la validación del cuerpo de la solicitud por usted.

about 4 years ago · Juan Pablo Isaza Relatório

0

Siguiendo con el comentario que dejé a continuación, esto es lo que puede hacer.

La refactorización de su código es imprescindible .

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

también podría simplemente:

 try { const userSaved = await newUser.save(); delete userSaved.password // assuming this is the property name return userSaved; }

En este caso, usted maneja el mensaje y todo en el front-end.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda