Here I have a function which through the error.
app.post(
"/restaurant/product/:product_id/images",
authOnly(),
authTo({ restaurant: true }),
reqParamHandler({
images: {
type: "array",
required: false
}
}),
(req, res, next) => {
const restaurant_id = req.user.id;
const product_id = req.params.product_id;
const image_ids = req.body.images;
Product.findOne({
_id: product_id,
restaurant: restaurant_id
}).exec((err, product) => {
if (err) res.sendStatus(500);
if (product) {
//Probably we need to check that image_ids belongs to restaurant_id
product.images = image_ids;
product.save((err, saved_product) => {
if (err) {
res.status(500).json({
message: err.message
});
}
if (saved_product) {
bindFiles(req.body.images, restaurant_id)
.then(() => {
File.find({ _id: { $in: image_ids } }, (err, files) => {
res.json({
data: files
});
});
})
.catch(err => {
res.status(500).json({
message: err.message
});
});
}
});
} else {
res.status(400).json({
message: "No product found. Please check parameters and try again."
});
}
});
}
);
The log looks as follows:
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (/home/omio/Apps/food/server/node_modules/express/lib/response.js:767:10)
at ServerResponse.send (/home/omio/Apps/food/server/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/home/omio/Apps/food/server/node_modules/express/lib/response.js:267:15)
at /home/omio/Apps/food/server/src/restaurant/restaurant.ts:1279:25
at /home/omio/Apps/food/server/node_modules/mongoose/lib/query.js:3122:9
at tryCatcher (/home/omio/Apps/food/server/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/omio/Apps/food/server/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/home/omio/Apps/food/server/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/home/omio/Apps/food/server/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/home/omio/Apps/food/server/node_modules/bluebird/js/release/promise.js:689:18)
at Async._drainQueue (/home/omio/Apps/food/server/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/home/omio/Apps/food/server/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues (/home/omio/Apps/food/server/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:794:20)
at tryOnImmediate (timers.js:752:5)
at processImmediate [as _immediateCallback] (timers.js:729:5)
Which cause the error NodeJS Error: Can't set headers after they are sent. This is because of the Promise (asynchronous function) i used... Yet don't know how to properly fix it... bindFiles is not setting any headers. Any ideas?