P
P
Pavel Tkachenko2018-09-26 20:00:50
JavaScript
Pavel Tkachenko, 2018-09-26 20:00:50

Why is Express returning an empty response?

There is a route on which the client registers... But the problem is that periodically the response from the server comes empty, it's not clear what this could be connected with. Here is the code itself:

// Require modules
var express                 = require('express');
var router                  = express.Router();
var mongoose                = require('mongoose');
var UserSchema              = require('../db/user');
var User                    = mongoose.model('user', UserSchema);
var validator               = require('validator');
var createError             = require('http-errors');

// Routes
router.route('/')
    .get((req, res, next) => {
        res.send(req.originalUrl);
    })
    .post((req, res, next) => {
        if( validator.isEmail(req.body.email) && 
            validator.isLength(req.body.password, 6, 18) &&
            validator.isLength(req.body.firstname, 3, 18) &&
            validator.isLength(req.body.lastname, 6, 18)) 
            {
            let user = {
                email       : req.body.email,
                password    : req.body.password,
                firstname   : req.body.firstname,
                lastname    : req.body.lastname,
                fathername  : req.body.fathername ? req.body.fathername : ''
            }
            new User(user).save()
                .then(() => {
                    res.send('Ok');
                })
                .catch((err) => {
                    if(err.code == 11000) {
                        res.status(422).send('User exists');
                    }
                    else {
                        err = createError(500)
                        return next(err)
                    }
                })
        }
        else {
            res.status(422).send('Invalid data');
        }
    })
module.exports = router;

I have suspicions that it somehow falls off the validator... Because the post request itself gets into the handler. Or mb to make the check in a separate function?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Tkachenko, 2018-09-27
@Pavel_Tkachenko

In short, I'm answering my own question ... Everything turned out to be much simpler, the validator does not work without notification if the data is undefined ...

G
grinat, 2018-09-26
@grinat

Do
try {
if(validadot...) {
await User(user).save()
}
} catch (err) {
console.error(err)
if (err.code == 11000) {
}
return next(createError(500) ))
}
If there is a problem with vaditors, you will immediately see

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question