0

I'm trying to setup register functionality using express on the server side and react on the client side. I did have it working with axios but had some issues with typescript so decided to see if it would be easier with the fetch API.

In my console I get this error:

Register.tsx:19 POST http://localhost:3000/users/register 422 (Unprocessable Entity)

Which makes sense from my server code because I haven't filled in the relevant fields, but for some reason nothing is happening in my catch block on the client side so I can display the errors.

I've checked in the network tab and the errors are definitely there in the response.

What am I missing?

React (Client side)

async function onHandleRegisterSubmit(e: any) {
        try {
            e.preventDefault();
            const response = await fetch('/users/register', {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });
            const data = await response.json();
            return data;
        } catch(err) {
            console.log(err);
        }
    }

Node/Express (Server side)

exports.validateUser = (req, res, next) => {
    req.sanitizeBody('name');
    req.checkBody('name', 'You must supply a name').notEmpty();
    req.sanitizeBody('email').normalizeEmail({});
    req.checkBody('email', 'That email is not valid').isEmail({
        remove_dots: false,
        remove_extension: false,
        gmail_remove_subaddress: false
    });
    req.checkBody('password', 'Password cannot be blank!').notEmpty();
    req.checkBody('password-confirm', 'Confirmed password cannot be blank!').notEmpty();
    req.checkBody('password-confirm', 'Oops! Your Passwords do not match!').equals(req.body.password);
    
    const errors = req.validationErrors();
    
    if(errors) {
        console.log(errors);
        return res.status(422).json(errors);
    }
    
    next(); // pass to register
}
Joe Consterdine
  • 1,035
  • 1
  • 18
  • 37
  • 1
    Fetch does not throw due to HTTP status codes that represent errors - it throws when there is a network communication issue. – Randy Casburn Dec 13 '20 at 23:39
  • You need to check the response status, eg `if (!response.ok) throw response;` – Phil Dec 13 '20 at 23:40

0 Answers0