SMEET KOTHARI
SMEET KOTHARI

Reputation: 69

How to solve unhandeled promise rejections?

error : UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token o in JSON at position 1
I m making a MERN stack app, In Frontend I have signup form and below given is POST method of it.

const onSignUp = async (e) => {            
        e.preventDefault();
        try {
            const body = {
                username,  
                email, 
                password, 
                firstname, 
                lastname, 
                country_code, 
                phone_no,  
                address, 
                city, 
                state, 
                country
            };
            console.log(typeof(JSON.stringify(body)));                        
            const response = await fetch("http://localhost:5000/api/user/create",{
                method : "POST",
                headers: {"Content-Type" : "application/json"},
                body: JSON.stringify(body)
            });            
            console.log(response);
        }
        catch (err) {
            console.error(err.message);
        }
    }

consider api/user in main index.js file and this route is created in user.js file.
and in Backend I have /create route is as follows:-

router.post('/create', async (req, res) => {
    const body = JSON.parse(req.body)
    console.log('backend'+typeof(req.body));
    try{        
        const {username, email, password, firstname, lastname, country_code, phone_no,  address, city, state, country} = req.body;
        const salt = await bcrypt.genSalt(10);
        const hashed_password = await bcrypt.hash(password, salt);
        const newUser = await pool.query(
            "INSERT INTO User_ (username, email, password, firstname, lastname, country_code, phone_no,  address, city, state, country) VALUES ($1, $2, $3, $4,$5, $6, $7, $8, $9, $10, $11) RETURNING user_id, username"
            [username, email, hashed_password, firstname, lastname, country_code, phone_no,  address, city, state, country]
        );
        res.status(201).send(newUser.rows[0]);
    }
    catch(err){
        console.log("Error : ", err);
    }
})

Upvotes: 0

Views: 74

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074355

I think there are two layers to this.

First, async functions always return promises. If an error is thrown in an async function, it rejects the promise the function returned. In your route handler, you have

const body = JSON.parse(req.body)

at the top level of the async function. That means any errors throwing parsing the JSON will be unhandled rejections.

You would want to move that line into the try/catch so that it's handled, since Express doesn't do anything with the promise you return. But, see the next item.

Second, your error message is the classic error you get when you call JSON.parse on something that's already been parsed and is an object, because JSON.parse converts its argument to string, and the string you get for plain objects is "[object Object]" — note the o at position 1 (0-based).

I suspect you have middleware installed that has already parsed the JSON for you, so you don't want to do that JSON.parse call at all. Just use the object on req.body.

Upvotes: 2

Related Questions