mardi 15 mai 2018

NodeJS, multiple if may return headers (and fails)

I'm running NodeJS and Express, and have the following code:

app.post(...)

    if (typeof req.body.input1 != "undefined") {
        // do something
        // if fails
        return res.json({ error: true });
    }

    if (typeof req.body.input2 != "undefined") {
        // do something
        // if fails
        return res.json({ error: true });
    }

    if (typeof req.body.input3 != "undefined") {
        // do something
        // if fails
        return res.json({ error: true });
    }

    return res.json({ error: false });

This fails (obviously) with:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): Error: Can't set headers after they are sent.

The reason I have 3 different if's are that my users may or may not have set 1, 2 or all 3 parameters as input (HTTP JSON API) - and I would like to handle each one independently.

How should I approach this the best way, so if input1 is set it will be handled, but throws an error if fails, then continue to input2 etc.

Aucun commentaire:

Enregistrer un commentaire