Wednesday 31 July 2019

Sending response status and json result in Headers Error

I posted my question on stack overflow but so far I haven't gotten a response. I'm trying to return a response of status and json if user didn't provide requirements to sign up return res.sendStatus(400).json({ errors: errors.array() });.I get an Error Can't set headers after they are sent to the client.If I remove one of chaining methods, then the response works normally. return res.json({ errors: errors.array() }); But I would like to include both.​Source code.const express = require('express'); const { check, validationResult } = require('express-validator'); const connectDB = require('./config/db'); const app = express(); // Connect to Database connectDB(); // Init Middleware app.use(express.json({ extended: false })); app.get('/', (req, res, next) => { res.send('API Runnning...'); }); // Define Routes app.use( '/api/users', [ check('name', 'Name is required') .not() .isEmpty(), check('email', 'Please include a valid email').isEmail(), check('password', 'Please enter a password at least 5 characters').isLength( { min: 5 } ), ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { console.log(errors); return res.sendStatus(400).json({ errors: errors.array() }); } const { name, email } = req.body; res.send('User route'); } ); const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`server listening on port ${PORT}`); });

Submitted August 01, 2019 at 01:41AM by Calligringer

No comments:

Post a Comment