I have done a lot of digging on this the last 2 days to not much avail.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I understand this to not really an issue with the headers but actually something is going wrong with sending multiple responses due to an issue the first time around. This was working before I started editing what was considered a valid request body.
exports.spend = (req, res, next) => {
if (valReq(req)) {
client(req)
.then((response) => {
res.status(response.status).send(response.data);
})
.catch(next);
} else {
res.status(403).send("Bad request");
}
};
Sending the request and routed to this function. The subsequent functions are below though when I log before the return in genReq everything seems ok. I can appreciate this is not a conventional setup so happy to share more info if needed.
exports.client = (req) => {
return apiConnect(genReq(req), req.headers, req.path).then(
(data) => {
return data;
}
);
};
exports.valReq = (req) => {
const requestHeaders = Object.keys(req.headers);
const requestJsonKeys = Object.keys(req.body);
for (const headerCheck of validHeaders) {
if (!requestHeaders.includes(headerCheck)) return false;
}
return (
_.xor(validRequestBody[req.path].inbound, requestJsonKeys).length === 0
);
};
const genReq = (req) => {
const validJsonData = validRequestBody[req.path].outbound;
const validJsonKeys = Object.keys(validJsonData);
const envJsonKeys = Object.keys(envJsonData)
const requestJson = req.body;
const request = {};
validJsonKeys.forEach((key) => {
request[key] = requestJson[validJsonData[key]];
});
envJsonKeys.forEach((key) => {
request[key] = envJsonData[key];
});
return request;
};
Thank you.