首页 > 解决方案 > 错误 [ERR_HTTP_HEADERS_SENT]:无法在将标头发送到客户端后设置标头,我无法将表单发送到实时数据库

问题描述

  1. 这是我的 html 代码提交
<form action="/user/product/add" method="POST" enctype="multipart/form-data" >
                        <h1 class="h">Add Product</h1>
                        <div>
                            <table class="tableez" cellpadding="4" cellspacing="0" style="width:400px">
                                <tr>
                
                                    <div class="form-group">
                                        <input type="file" name="imageProduct" multiple>
                                    </div>
                                </tr>
                                <tr>
                                    <td class="tdtitle">Tên sản phẩm: </td>
                                    <td><input type="text" value="{{data.nameProduct}}" name="nameProduct"
                                            id="nameProduct">
                                    </td>
                                </tr>
                        <button type="submit" class="btn btn-primary">Thêm</button>
                    </form>
  1. 这是我的 api
router.post('/product/add', upload.array('imageProduct', 5), isLoggedIn, function (req, res, next) {
 
    var idd = "5ea4528ccaf1ab0017e0fe22";
    var filesImage = req.files;
    var images = [];
    filesImage.forEach(function (item, index, array) {
      images.unshift(item.filename);
    });
    var winner = [];
    winner.unshift("1");
    winner.unshift("Chưa có");
    //  var messages = [];
    // messages.unshift({
    //     a : "qwe",
    //     b : "asdq"
    // });

    var played = [];
    played.unshift("null");
    var registerDatee = Date.now();
    var time = req.body.time;
    console.log(time);
    const product = {
      imageProduct: images,
      nameProduct: req.body.nameProduct,
      userId: idd,
      nameProductType: req.body.cars,
      startPriceProduct: req.body.currentPrice,
      status: req.body.status,
      description: req.body.description,
      extraTime: req.body.time,
      registerDate: registerDatee,
      winner: winner,
      hide: false,
      currentPrice: req.body.currentPrice,
      played: played
    };

    var db = Firebase.database();
    var rootRef = db.ref('products');
    rootRef.push(product);
    res.redirect('/');

});

单击提交后,出现以下错误 3. 这是我的错误

POST /user/product/add 200 151.592 ms - -
_http_outgoing.js:526
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:526:11)
    at ServerResponse.header (C:\Users\HaAnh\Desktop\api\backend-app-daugia\node_modules\express\lib\response.js:767:10)
    at ServerResponse.contentType (C:\Users\HaAnh\Desktop\api\backend-app-daugia\node_modules\express\lib\response.js:595:15)
    at ServerResponse.send (C:\Users\HaAnh\Desktop\api\backend-app-daugia\node_modules\express\lib\response.js:145:14)
    at done (C:\Users\HaAnh\Desktop\api\backend-app-daugia\node_modules\express\lib\response.js:1004:10)
    at Immediate._onImmediate (C:\Users\HaAnh\Desktop\api\backend-app-daugia\node_modules\express-handlebars\lib\utils.js:26:4)
    at processImmediate (internal/timers.js:456:21) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...

不明白为什么我提交后就报错了,但是改掉就好了,上面的问题看了很多,但是我的项目还是没有解决办法。我哭了,因为我不知道下一步该做什么。 尽管发生了错误,但该产品已保存在数据库中。 请给我一个解决方案,以便我可以继续我的项目!

标签: javascriptnode.jsexpress

解决方案


这看起来是 Node.js 中非阻塞 I/O 的一个经典问题。你需要将你的工作包装在一个 Promise 中。

new Promise(function(resolve, reject) {
  //do the file work
  var idd = "5ea4528ccaf1ab0017e0fe22";
  var filesImage = req.files;
  var images = [];
  filesImage.forEach(function (item, index, array) {
    images.unshift(item.filename);
  });
  // more work here
  return true; //after the work is done
})
.then(() => {
  // do more work here if needed
});
.then(() => {
  // after the I/O work is done
  res.redirect('/');
});

我没有仔细检查语法,但你可以从我的片段中得到这个想法。


推荐阅读