I'm encountering an issue with my code where I am unable to make a fetch request when invoking sendPushMessages(message) due to HTTP ERRORS, but I am unsure of the root cause.
The console is displaying the following error message: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Furthermore, if I comment out the line: res.status(200).send({shop: shop[0]}); the code still does not work.
const {models} = require('../models');
const Sequelize = require('sequelize');
exports.findshop = async (req, res, next) => {
sendPushMessages = async (message) => {
try{
let response = await fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-encoding': 'gzip, deflate',
'Content-Type': 'application/json',
},
body: JSON.stringify(message),
});
let responseData = await response.json();
console.log(responseData);
}
catch (error) {
next(error);
}
}
try {
console.log(req.body.latitud)
console.log(req.body.longitud)
const user = req.user;
const shops = await models.Shop.findAll({
include:[{ model: models.Product, as: 'placements'}]
});
const shop = shops.filter(shp => {
if (Math.abs(shp.latitud - req.body.latitud) <= 0.001 && Math.abs(shp.longitud - req.body.longitud) <= 0.001){
return shp;
}
});
if (shop[0] && user) {
shop[0].placements.forEach(item => {
if (item.dataValues.isoffer){
const message = {
to: user.pushtoken,
sound: 'default',
title: 'Big Sale Alert! Don't Miss Out!',
body: item.productname + ' ' + item.price.toString() + '€',
};
sendPushMessages(message);
}
})
res.status(200).send({shop: shop[0]});
} else {
res.status(200).send({shop: null});
}
} catch (error) {
next(error);
}
};