【问题标题】:express js set request header Content-Type in middleware based on file extension?express js 在基于文件扩展名的中间件中设置请求头 Content-Type?
【发布时间】: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。

我在这里做错了什么?

【问题讨论】:

  • 此中间件是否位于您要向其发出请求的端点的路由器之前?
  • 是的,我已经确定,它之前已经定位了。

标签: node.js express


【解决方案1】:

因此,非持久性内容内容类型不是问题。其实 content-type 是有的,但是由于关注了错误的问题,我很困惑。

无论如何,真正的“问题”是,请求标头的接受字段中没有标头 mime 类型。

如果没有设置 express 并且任何其他健全的网络服务器都不会识别它。

这是我需要做的:

module.exports = function fileExtensionHeader(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;
      req.headers.accept = `${contentType},${req.headers.accept}`; // this line did the trick
   }
   next();
};

一句警告:

这会带来潜在的安全风险。 mime 类型只能由浏览器发送的请求头设置。

任何人都不应允许在没有充分理由的情况下通过文件扩展名设置 MIME 类型。

【讨论】:

    猜你喜欢
    • 2015-06-22
    • 2017-03-29
    • 2011-07-21
    • 2017-11-13
    • 2014-05-23
    • 1970-01-01
    • 2019-05-01
    • 2012-05-27
    相关资源
    最近更新 更多