Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

223
Views
no se puede establecer el estado de 400 en express

Tengo un servicio web simple y tiene una ruta para registrar usuarios,

Quiero que cuando exista un correo electrónico en la base de datos, arroje un error con el estado 400 u otro

lo he hecho asi

controladores/usuario.js

 const { User } = require('../models/user') exports.create = async (req, res) => { try { const { email } = req.body const user = await User.findOne({ email }) if (user) { return res.json({ err: 'email already exists' }) } await User.userValidation(req.body) await User.create(req.body) return res.json({}) } catch (err) { res.status(400).send({ err }) } }

PERO, siempre da el estado de 200,

Dónde está el problema ?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Agregue el estado a su respuesta:

 if (user) { return res.status(400).json({ err: 'email already exists' }) }
over 4 years ago · Santiago Trujillo Report

0

Simplemente puede enviar el estado 400 al verificar if(user)

 if(user){ res.status(400).jsom({ err: "Email already exists" }); }

O Amenace los errores y agregue un middleware usando next (un poco más complicado que el primero, pero más profesional)

 exports.create = async (req, res, next) => { try { const { email } = req.body const user = await User.findOne({ email }) if (user) { throw new Error("Email already exists"); } await User.userValidation(req.body) await User.create(req.body) return res.json({}) } catch (err) { next(err, req, res, next); } }

En el siguiente middleware, puede amenazar con el error y enviar la respuesta que necesite. (err, req, los objetos res se envían como referencias, por lo que puede usarlos allí)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!