为什么我在 NodeJS 中收到此意外的 HTTP 错误

Why am I getting this UNEXPECTED HTTP error in NodeJS

伙计们,我正在为一个电子商务网站在 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 class 包含以下方法:

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)

                    }

                })

        })


    }

orderData 方法中的 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, (err, result) => {

        if (err) {

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

        } else {

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

        }

    })


})

当我尝试(一次)从我的前端(和 Postman)下订单时它工作正常。

但问题是,每当我尝试(再次)下订单时,我都会收到 [ERR_HTTP_HEADERS_SENT] 错误。貌似只能下单一次,废话

我真的不知道出了什么问题,这让我无法继续关注我的项目的其他问题,需要帮助。

谢谢

我认为问题在于您使用 orderData.products.map((product) => {... 迭代产品,并且对于您调用 callbackfn 的每个产品,后者又调用 res.json({...})。因此,对于每个产品,都会调用 res.json({...}),但我认为每个请求只能调用一次。

在客户端中尝试这样的操作 class:

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'] }))