'Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client POST HTTP REQUEST

Need some help with this. So im following a tutorial but im facing this error. So im doing a post http request with POSTMAN this is my body

 {
   
 "userId": "2",
 
   "products":
 
   [{"id":"2", "incart":"5"}, {"id": "3", "incart": "8"}]
}

this is my orders.js im using mysqli to connect to my mysql BD

    router.post('/new', (req, res) => {

    let {userId, products} = req.body;

    if (userId !== null && userId > 0 && !isNaN(userId)) {
        database.table('orders')
            .insert({
                user_id: userId
            }).then(newOrderId => {

            if (newOrderId > 0) {
                products.forEach(async (p) => {

                    let data = await database.table('products').filter({id: p.id}).withFields(['quantity']).get();

                    let inCart = p.incart;

                    //    Deduct the number of pieces ordered from the quantity column in database
                    if (data.quantity > 0) {
                        data.quantity = data.quantity - inCart;

                        if (data.quantity < 0) {
                            data.quantity = 0;
                        }

                    } else {
                        data.quantity = 0;
                    }

                    //    INSERT ORDER DETAILS W.R.T THE NEWLY GENERATED ORDER ID
                    database.table('orders_details')
                        .insert({
                            order_id: newOrderId,
                            product_id: p.id,
                            quantity: inCart
                        }).then(newId => {
                        database.table('products')
                            .filter({id: p.id})
                            .update({
                                quantity: data.quantity
                            }).then(successNum => {
                        }).catch(err => console.log(err));
                    }).catch(err => console.log(err));

                });
            } else {
                res.json({message: 'new order failed while adding order details', success: false})
            }
            res.json({
                message: `Order successfully placed with order id ${newOrderId}`,
                success: true,
                order_id: newOrderId,
                products: products
            });
        }).catch(err => console.log(err));
    } else {
        res.json({message: 'New order failed', success: false});
    }


});

Also postman response is new order failed while adding order.

In console is getting the following error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Any helpers would be appreciated



Solution 1:[1]

This is happening because you are resetting the res after it is sent.

                });
            } else {
    Here u are setting it once ---->>> res.json({message: 'new order failed while adding order details', success: false})
            }
            res.json({
                message: `Order successfully placed with order id ${newOrderId}`,
                success: true,
                order_id: newOrderId,
                products: products
            }); //<<<<---- You are resetting the response after it is sent

You should return res.json({}) instead of just res.json({}). This will prevent resetting of response.

                });
            } else {
    return it just from here ---->>> return res.json({message: 'new order failed while adding order details', success: false})
            }
            return res.json({
                message: `Order successfully placed with order id ${newOrderId}`,
                success: true,
                order_id: newOrderId,
                products: products
            }); //<<<<---- now, You are not resetting the response after it is sent


Here, I have explained it using this example.

const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/:condition", (req, res) => {
    if (req.params.condition === "true") {
        return res.json({ success: true, msg: "setting true" });
    } else return res.json({ success: false, msg: "setting false" });
    res.json({ success: false, msg: "setting again" });
});

app.listen(8080, function () {
    console.log("Server is running on 8080");
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Himanshu Singh