Why am I getting this UNEXPECTED HTTP error in NodeJS

Tags: , , , ,



So guys i’m setting up my backend in NodeJS for an e-commerce website. But I ran into an error trying to implement the “Order” method.

First the connection to mysql database :

let mysql = require('mysql')

let connection = mysql.createConnection({

    host: 'localhost',
    user: 'root',
    password: '',
    database: 'ecom_new'

})

connection.connect()

module.exports = connection

Then in my Models there is a Client class that contains the following method :

static order(orderData, callbackfn) {

        orderData.products.map((product) => {

            connection.query(`INSERT INTO orders SET
                product_name = ?, owner = ?, quantity = ?, price = ?, client_name = ?, client_phone = ?, client_address = ?`,
                [product.name, product.owner, product.count,product.price, orderData.clientName, 
                orderData.clientPhone, orderData.clientLoc], (err, result) => {

                    if (err) {

                        callbackfn(err)

                    } else {

                        callbackfn(null, result)

                    }

                })

        })


    }

The orderData parameter in the order() method is a JSON posted from the frontend, that looks like this:

{
    "products": [
        {"name": "Item 1", "owner": "Clint", "count": 1, "price": 150},
        {"name": "Item 2", "owner": "Steve", "count": 3, "price": 350},
        {"name": "Item 3", "owner": "Bruce", "count": 6, "price": 110}
     ],

    "clientName": "Tony Stark",
    "clientPhone": "111111",
    "clientLoc": "Malibu"
}

And finally the route that handles this request is coded like this :

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


    Client.order(req.body, (err, result) => {

        if (err) {

            res.json({RequestResult: 'ERROR', Message: err['sqlMessage']})

        } else {

            res.json({RequestResult: 'SUCCESS', Message: 'New order placed successfully'})

        }

    })


})

It works just fine when I try (once) to place an order from my frontend (and Postman).

But the issue is that whenever I try (again) to place an order i’m getting the [ERR_HTTP_HEADERS_SENT] error. Looks like i can only place an order once, which is nonsense.

I don’t really know what is wrong and it is keeping me from moving on to other concerns of my project, help is needed.

Thanks

Answer

I think the problem is that you iterate over the products with orderData.products.map((product) => {... and for each product you call the callbackfn which in turn calls res.json({...}). So for each product a res.json({...}) is called but i think you are only allowed to call it once per request.

Try something like this in the Client class:

static order(orderData) {
  return Promise.all(orderData.products.map((product) => {
    return new Promise((resolve, reject) => {
      //run query
      if (err) reject(err)
      else resolve()
    })
  }))
}

now you can use this function like so:

Client.order(req.body)
  .then(() => res.json({ RequestResult: 'SUCCESS', Message: 'New order placed successfully' }))
  .catch(err => res.json({ RequestResult: 'ERROR', Message: err['sqlMessage'] }))


Source: stackoverflow