The end points of my API-application render data based on the request mime type. I have implementing express' response.format() to distinguish between the req types.
However, the handler also needs to be able to distinguish the formats based on the file extension like
/route/users.json
Express' response.format doesn't handle that case.
Therefore I was hoping I could simply use a middleware function and set the headers Content-Type according to the extension like this:
app.use('/', (req, res, next) => {
let contentType;
if (req.path.match(/\.json/)) {
contentType = 'application/json';
} else if (req.path.match(/\.xml/)) {
contentType = 'text/xml';
}
if (contentType) {
req.headers['Content-Type'] = contentType;
}
next();
});
But that's not working. I have checked whether the middleware is actually executed and that's the case. However the Content-Type does not persist.
So when the actual request handler is being executed the Content-Type is missing.
What am I doing wrong here?