如何在 Sails.js 应用程序中禁用或替换 X-Powered-By 标头

How to disable or replace X-Powered-By header in Sails.js application

本文关键字:替换 X-Powered-By 标头 Sails js 应用程序      更新时间:2023-09-26

当我运行 Sails.js 应用程序时,它会自动将以下 HTTP 标头添加到每个响应中:X-Powered-By: "Sails <sailsjs.org>"

是否可以禁用或覆盖它?

编辑config/http.js并将poweredBy设置为 false

module.exports.http = {
  middleware: {
    poweredBy: false
  }
}

由于 Sails 将禁用快速的 X-Powered-By 标头,因此无需手动禁用它。

是的,这是很有可能的。

您需要禁用名为 poweredBy 的 Sails 中间件.js并告诉 Express 服务器不要添加自己的标头。

只需将config/http.js配置文件更新为如下所示:

module.exports.http = {
  middleware: {
    disablePoweredBy: function(request, response, next) {
      var expressApp = sails.hooks.http.app;
      expressApp.disable('x-powered-by');
//    response.set('X-Powered-By', 'One Thousand Hamsters');
      next();
    },
    order: [
//    ...
//    'poweredBy',
      'disablePoweredBy',
//    ...
    ]
  }
};

在这里,我们从 Sails 钩子中检索快速应用程序的实例,然后使用它disable()方法将x-powered-by配置参数设置为false值。这将阻止标题出现。

为了启用此自定义中间件,您需要将其添加到order数组中。您可以将poweredBy中间件替换为 disablePoweredBy

此外,通过取消注释 response.set() 方法,您可以设置自己的标头值。

无需创建新的中间件,例如,您可以覆盖 Sails 的 poweredBy 中间件.js

module.exports.http = {
  middleware: {
    poweredBy:  function (req, res, next) {
      // or uncomment if you want to replace with your own
      // res.set('X-Powered-By', "Some Great Company");      
      return next();
    }
  }
}