我在 Node.js 中使用 swagger 来获取 API 文档。 现在我想使用头盔来确保安全,但是当我使用头盔时,会出现错误。 但是,如果我将头盔放置在 swagger 的路由器下方,那么它工作正常,这意味着头盔会执行某些操作,使 swagger-ui 不会被加载。
下面的代码是我如何使用头盔。
var helmet = require('helmet')
app.use(helmet());
下图是 swagger 的错误
修复以允许 cors,但仍然出现错误。
//allow cors
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// use helmet
var helmet = require('helmet')
app.use(helmet());
您需要启用 CORS ,以便它在响应中发送 Access-Control-Allow-Origin: * 标头。 CORS 代表跨源资源共享。它开放了我们打算向公众提供的内容,以供通用 JavaScript/浏览器访问。
示例:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
在设置 HelmetJS 中间件之前,请务必确保渲染 Swagger UI 模板,以避免出现问题。
// before
const document = SwaggerModule.createDocument(app, new DocumentBuilder().build());
SwaggerModule.setup('docs', app, document);
// then
app.use(helmet());