为什么我在NodeJS中收到此UNEXPECTED HTTP错误

问题描述

所以,伙计们,我正在NodeJS中为电子商务网站设置后端。 但是我在尝试实现“ Order”方法时遇到错误

首先连接到MysqL数据库

let MysqL = require('MysqL')

let connection = MysqL.createConnection({

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

})

connection.connect()

module.exports = connection

然后在我的模型中有一个 Client 类,其中包含以下方法

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)

                    }

                })

        })


    }

order()方法中的 orderData 参数是从前端发布的JSON,如下所示:

{
    "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"
}

最后,处理此请求的路由如下所示:

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


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

        if (err) {

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

        } else {

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

        }

    })


})

当我尝试(一次)从前端(和邮递员)下订单时,效果很好。

但是问题是,每当我尝试(再次)下订单时,我都会遇到 [ERR_HTTP_HEADERS_SENT] 错误。看来我只能下订单一次,这是胡说八道。

我真的不知道出什么问题了,这使我无法继续从事项目的其他工作,需要帮​​助。

谢谢

解决方法

我认为问题在于,您使用orderData.products.map((product) => {...遍历产品,并为每个产品调用callbackfn,而依次调用res.json({...})。因此,对于每个产品,都会调用res.json({...}),但我认为您只能在每个请求中调用一次。

在Client类中尝试类似的事情:

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

现在您可以像这样使用此功能:

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