【发布时间】:2021-04-13 01:37:26
【问题描述】:
我的 API 应用程序根据请求 mime 类型呈现数据的端点。我已经实现了 express 的 response.format() 来区分 req 类型。
但是,处理程序还需要能够根据文件扩展名区分格式,例如
/route/users.json
Express 的 response.format 不处理这种情况。
因此,我希望我可以简单地使用中间件函数并根据扩展名设置标题 Content-Type,如下所示:
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();
});
但这不起作用。我检查了中间件是否实际执行,就是这样。但是 Content-Type 不会持续存在。
因此,当实际的请求处理程序正在执行时,缺少 Content-Type。
我在这里做错了什么?
【问题讨论】:
-
此中间件是否位于您要向其发出请求的端点的路由器之前?
-
是的,我已经确定,它之前已经定位了。