I need to change the status code on some responses before passing them on based on the data in them. Their body is a JSON object containing a field that determines this. I have only found a way (using middleware) to change the body content:
const app = express()
.use(function (req, res, next) {
var _write = res.write;
res.write = function (data) {
_write.call(res, (data) => {/*some function that returns modified data*/});
}
next();
}
However I found no way to change the status code and status message. Doing this:
res.statusCode = 400
has no effect on the response my client receives.
+1
I was able to do this by overriding the writeHead function
// Avoid setting cookie from core (stateless behaviour)
coreProxy.on('proxyRes', (proxyRes, req, res) => {
const originalWriteHead = res.writeHead;
const originalWrite = res.write;
const originalEnd = res.end;
let jsonString = '';
Object.assign(res, {
writeHead: () => {},
write: (chunk) => {
jsonString += chunk.toString();
},
end: () => {
// remove set-cookie header
const headers = Object
.keys(proxyRes.headers)
.reduce((acc, key) => {
const value = key === 'set-cookie' ? [] : proxyRes.headers[key];
return Object.assign({}, acc, { [key]: value });
}, {});
const originalJSONResponse = JSON.parse(jsonString);
// determine the status code base on error class name
let statusCode = 200;
if (originalJSONResponse.error) {
const { errorClassName } = originalJSONResponse;
switch (errorClassName) {
case 'NeedsToBeDisplayedToUserException':
statusCode = 400;
break;
case 'NotFoundException':
statusCode = 404;
break;
default:
statusCode = 500;
}
}
originalWriteHead.apply(res, [statusCode, headers]);
originalWrite.call(res, new Buffer(JSON.stringify(originalJSONResponse)));
originalEnd.call(res);
},
});
});
// Proxy requests with url patten (*/core/*) to core (in a stateless fashion)
app.use((req, res, next) => {
if (req.originalUrl.indexOf('/core/') !== -1) {
coreProxy.web(req, res);
} else {
next();
}
});
Most helpful comment
I was able to do this by overriding the writeHead function